#include "qggrifodownloadentitiesform.h"
#include "ui_qggrifodownloadentitiesform.h"

#include <QStandardItemModel>
#include <QStandardItem>

#include <QProgressBar>

#include <QDropEvent>
#include <QDragEnterEvent>
#include <QMimeData>

#include "bsk_tftp_pfs.h"

#include <QHostAddress>
#include "mydebug.h"

//definition of columns for table
#define COL_TARGET  0
#define COL_ADDRESS 1
#define COL_AREA    2
//#define COL_SECTION 3

void QgGrifoDownloadEntitiesForm::db_add_site(QTreeWidget* root, QgGrifoDownloadSite* s)
{
    QTreeWidgetItem* item=new QTreeWidgetItem(root);
    bsk_download_site_t* site=&s->site;

    item->setText(COL_TARGET, site->name);
    item->setData(COL_TARGET, Qt::UserRole, (unsigned long long)site);
    item->setToolTip(COL_TARGET, QString("%1 (%2)").arg(s->tgtFlash->description).arg(s->tgtFlash->name));
    item->setText(COL_ADDRESS, QString("%1@%2:%3")
                  .arg(site->address)
                  .arg(QHostAddress(site->media_address).toString())
                  .arg(site->media_port));

    item->setText(COL_AREA, QString("%1 - %2")
                  .arg(s->tgtFlash->model.userAddressStartArea)
                  .arg(s->tgtFlash->model.userAddressStopArea));

    item->setCheckState(COL_TARGET, Qt::Unchecked);

    s->tgtFlash->wi=item;
}

QString ShowFileInfo(const QString& fname, bool popup=true);

QgGrifoDownloadEntitiesForm::QgGrifoDownloadEntitiesForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QgGrifoDownloadEntitiesForm)
{
    ui->setupUi(this);

    ui->treeWidget->setColumnCount(3);
    ui->treeWidget->headerItem()->setText(COL_TARGET, "Target");
    ui->treeWidget->headerItem()->setText(COL_ADDRESS, "Address");
    ui->treeWidget->headerItem()->setText(COL_AREA, "Flash area");
    ui->treeWidget->header()->setSectionResizeMode(COL_TARGET,QHeaderView::ResizeToContents);
    ui->treeWidget->header()->setSectionResizeMode(COL_ADDRESS,QHeaderView::ResizeToContents);
    ui->treeWidget->header()->setSectionResizeMode(COL_AREA,QHeaderView::ResizeToContents);

    ui->treeWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);

    //ui->treeView->setC
    connect(ui->treeWidget, &QTreeWidget::itemDoubleClicked, this,
            [this](QTreeWidgetItem *item, int column)
    {       
       if (column==0)
       {
            unsigned long long s=item->data(0, Qt::UserRole).toULongLong();
            unsigned long long p=item->data(0, Qt::UserRole+1).toULongLong();

            Q_EMIT itemSelected((void*)s, (void*)p);
       }
       else if (column==3)
       {
           //ShowFileInfo(item->toolTip(3));
       }
    });

    this->setAcceptDrops(true);
}

QgGrifoDownloadEntitiesForm::~QgGrifoDownloadEntitiesForm()
{
    delete ui;
}

//***********************************************************************
// Add site target to send file for fpga-flash
// Input parameters:    s = struct of new target
// Returns:
//***********************************************************************
void QgGrifoDownloadEntitiesForm::addSite(const QgGrifoDownloadSite *s)
{
    db_add_site(ui->treeWidget, (QgGrifoDownloadSite*)s);
}

//***********************************************************************
// Clear all target from the treewidget
// Input parameters:
// Returns:
//***********************************************************************
void QgGrifoDownloadEntitiesForm::clear()
{
    ui->treeWidget->clear();
}

void QgGrifoDownloadEntitiesForm::dragEnterEvent(QDragEnterEvent * event)
{
    if (event->mimeData()->hasUrls())
    {
        QList<QUrl> lst=event->mimeData()->urls();
        if ((lst.size()>0) && lst.size()<10)
        {
              event->acceptProposedAction();
              MyDebug<<"T Drop accepct";
        }
    }
}

void QgGrifoDownloadEntitiesForm::dropEvent(QDropEvent * event)
{
    QList<QUrl> lst=event->mimeData()->urls();
    if (lst.size()>0)
    {
        for(int i=0; i<lst.size(); ++i)
        {
            if (lst.at(i).isLocalFile())
            {
                MyDebug<<"T Drop"<<lst.at(i).toLocalFile();
                QPoint p=QCursor::pos();
                QTreeWidgetItem* wi=ui->treeWidget->itemAt(ui->treeWidget->viewport()->mapFromGlobal(p));
                if (i)
                {
                    MyDebug<<"I"<<wi->text(0);
                }
                Q_EMIT fileDroppped(wi, lst.at(i).toLocalFile());
            }
        }
    }
}

//***********************************************************************
// Select Default Target into List of available targets
// Input parameters:    _def_target = search target with this string into targetSection
//
// Returns:
//***********************************************************************
void QgGrifoDownloadEntitiesForm::setDefaultTarget(QString _def_target)
{
    QTreeWidgetItemIterator it(ui->treeWidget);

    while(*it)
    {
        QTreeWidgetItem* item = *it;
        if(item && item->text(0) == _def_target)
        {
            item->setCheckState(COL_TARGET, Qt::Checked);
            break;
        }
        ++it;
    }
}

//***********************************************************************
// Get first target are selected into treeWidget
// Input parameters:
//
// Returns:                 target name
//***********************************************************************
QString QgGrifoDownloadEntitiesForm::getFirstSelectedTarget()
{
    QTreeWidgetItemIterator it(ui->treeWidget);

    while(*it)
    {
        QTreeWidgetItem* item = *it;
        if(item && item->checkState(COL_TARGET)==Qt::Checked)
        {
            return item->text(0);
            break;
        }
        ++it;
    }

    return "";
}

//***********************************************************************
// Select Default Target into List of available targets
// Input parameters:    _def_target = search target with this string into targetSection
//
// Returns:
//***********************************************************************
void QgGrifoDownloadEntitiesForm::setChecked(QString _def_target)
{
    QTreeWidgetItemIterator it(ui->treeWidget);

    while(*it)
    {
        QTreeWidgetItem* item = *it;
        if(item && item->text(0) == _def_target)
        {
            item->setCheckState(COL_TARGET, Qt::Checked);
        }
        ++it;
    }
}

void QgGrifoDownloadEntitiesForm::setUnCheckedAll()
{
    QTreeWidgetItemIterator it(ui->treeWidget);

    while(*it)
    {
        QTreeWidgetItem* item = *it;

        item->setCheckState(COL_TARGET, Qt::Unchecked);

        ++it;
    }
}
