#include "mlineeditbutton.h"
#include "widgetcomboboxpopuptable.h"
#include "mapplication.h"
#include "../mainwindow.h"
#include "formproduct.h"
#include "msqlquerymodel.h"

#include <QAction>
#include <QtSql>

MLineEditButton::MLineEditButton(QWidget *parent) :
    QLineEdit(parent)
{
    QAction *myAction = addAction(QIcon(":/resources/icons/down-arrow.svg"), QLineEdit::TrailingPosition);
    connect(myAction, &QAction::triggered, this, &MLineEditButton::onPopupShow);
}

void MLineEditButton::onPopupShow()
{
    auto *popup = new widgetComboboxPopupTable(this);
    popup->setModel(new MSqlQueryModel());

    connect(popup->buttonNew, &QPushButton::released, this, &MLineEditButton::onPopupNewButton_release);
    connect(popup->buttonEdit, &QPushButton::released, this, &MLineEditButton::onPopupEditButton_release);
    connect(popup, &widgetComboboxPopupTable::onSelect, this, &MLineEditButton::getValuesFromPopup);

    popup->setQueryEXEC("SELECT TYPE1, TYPE2, CODE, TITLE, UNIT_ID, PURCHASE_PRICE, SALE_PRICE FROM ELEMENT;");
    popup->tableView->setColumnWidth(0, 40);
    popup->tableView->setColumnWidth(1, 70);
    popup->tableView->setColumnWidth(2, 120);
    popup->tableView->setColumnWidth(3, 250);
    popup->tableView->setColumnWidth(4, 50);
    popup->tableView->setColumnWidth(5, 70);
    popup->tableView->setColumnWidth(6, 70);

    popup->tableView->horizontalHeader()->model()->setHeaderData(0, Qt::Horizontal, tr("Tipo"));
    popup->tableView->horizontalHeader()->model()->setHeaderData(1, Qt::Horizontal, tr("Clase"));
    popup->tableView->horizontalHeader()->model()->setHeaderData(2, Qt::Horizontal, tr("Código"));
    popup->tableView->horizontalHeader()->model()->setHeaderData(3, Qt::Horizontal, tr("Resumen"));
    popup->tableView->horizontalHeader()->model()->setHeaderData(4, Qt::Horizontal, tr("Coste"));
    popup->tableView->horizontalHeader()->model()->setHeaderData(5, Qt::Horizontal, tr("Venta"));
    popup->tableView->horizontalHeader()->model()->setHeaderData(6, Qt::Horizontal, tr("Activo"));


    popup->move(mapToGlobal(rect().bottomLeft()).x(),
                mapToGlobal(rect().bottomLeft()).y());
    popup->show();
}

void MLineEditButton::onPopupNewButton_release()
{
    formProduct *form = dApp->mainWindow()->createFormProduct();
    form->show();
}

void MLineEditButton::onPopupEditButton_release()
{
    /*
    QModelIndex item = index;
    formProduct *form = dApp->mainWindow()->createFormProduct();

    if (index.column() != 0)
        item = index.parent().child(index.row(), 0);
    form->openDocument(index.data().toString());
    form->show();
    */
}

void MLineEditButton::getValuesFromPopup(QStringList list)
{
    setText(list[0]);

    // TODO: si devuelve más de uno - ver como se hace
    /*
    for(auto item : list)
    {
        setText(item);
        qDebug() << item;
    }
    */
}



