#include "shopsettingsform.h"
#include "ui_shopsettingsform.h"

#include <settingsservice.h>
#include <combodata.h>
#include <QFileDialog>
#include <QDragEnterEvent>
#include <QDebug>
#include "shopservice.h"
#include "shop-odb.hxx"


ShopSettingsForm::ShopSettingsForm(QWidget *parent) :
    FormBinder<ShopSettings>(parent),
    ui(new Ui::ShopSettingsForm)
{
    ui->setupUi(this);

    registerBinding(ui->output);
    registerBinding(ui->lettersPerLine);
    registerBinding(ui->byMessage);

    registerBinding(ui->eetActive);
    registerBinding(ui->eetShopId);
    registerBinding(ui->eetRegisterId);
    QList<ComboData> listModes;
    listModes << ComboData(0, tr("Simplifyed")) << ComboData(1, tr("Standard"));
    registerBinding(ui->eetMode, listModes);
    registerBinding(ui->eetCertificate);
    registerBinding(ui->eetKeyPassword);
    registerBinding(ui->eetTest);
    registerBinding(ui->eetPlayground);

    registerBinding(ui->favBtnCols);
    registerBinding(ui->favBtnRows);
    registerBinding(ui->favBtnSize);

    m_itemModel = new AutoTableModel<ShopItem>();
}

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

void ShopSettingsForm::drawButtons()
{
    foreach (QWidget *child, ui->btnWidget->findChildren<QWidget*>()) {
        delete child;
    }

    for (int i = 0; i < entity()->favBtnRows(); i++)
    {
        for (int j = 0; j < entity()->favBtnCols(); j++)
        {
            FavButton *btn = new FavButton(ui->btnWidget);
            btn->setObjectName(QString::number(i) + "_" + QString::number(j));
            btn->setAcceptDrops(true);

            if (m_btnMap[btn->objectName()] != NULL)
            {
                btn->setText(m_btnMap[btn->objectName()]->shortName());
            }

            if (entity()->favBtnSize() > 0)
            {
                btn->setMinimumHeight(entity()->favBtnSize());
                btn->setMinimumWidth(entity()->favBtnSize());
            }
            ((QGridLayout*)ui->btnWidget->layout())->addWidget(btn, i, j);

            connect(btn, &FavButton::clicked, [this, btn](bool){
                btn->setText("");
                m_btnMap.remove(btn->objectName());
            });

            connect(btn, &FavButton::itemDropped, [this, btn](){
                ShopItemPtr item = m_itemModel->itemFromIndex(ui->tableItems->currentIndex());
                FavoritItemPtr favItem = QSharedPointer<FavoritItem>(new FavoritItem);
                favItem->setFavButtonName(btn->objectName());
                favItem->setName(item->name());
                favItem->setShortName(item->shortName());
                favItem->setRefId(item->id());
                favItem->setPluginId(item->pluginId());
                m_btnMap[btn->objectName()] = favItem;
                btn->setText(item->shortName());
            });
        }
    }
}

void ShopSettingsForm::loadEntity()
{
    SettingsService srv("SHOP");
    ShopSettingsPtr settings = srv.loadSettings<ShopSettings>();
    setEntity(settings);

    ShopService srvShop;
    m_itemModel->setData(srvShop.allSellableItems());
    m_itemModel->setTranslations(Context::instance().plugin("SHOP")->translations());
    ui->tableItems->setModel(m_itemModel);
    ui->tableItems->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    ui->tableItems->setColumnHidden(0, true);
    ui->tableItems->setColumnHidden(2, true);
    ui->tableItems->setColumnHidden(4, true);

    Service<FavoritItem> srvFav;

    foreach (FavoritItemPtr favItem, srvFav.all()) {
        m_btnMap[favItem->favButtonName()] = favItem;
    }
    drawButtons();
}

bool ShopSettingsForm::saveRecord()
{
    bindToData();
    SettingsService srv("SHOP");
    srv.saveSettings(entity());

    Service<FavoritItem> srvFav;
    foreach (FavoritItemPtr item, srvFav.all()) {
        srvFav.erase(item);
    }

    foreach (QString btnName, m_btnMap.keys()) {
        if (m_btnMap[btnName] != NULL)
        {
            srvFav.save(m_btnMap[btnName]);
        }
    }

    return true;
}

void ShopSettingsForm::on_btnCertBrowse_clicked()
{
    QString certFile = QFileDialog::getOpenFileName(this, "Certificate file", "", "P12 Files (*.p12)");

    if (!certFile.isEmpty())
    {
        ui->eetCertificate->setText(certFile);
    }
}

void ShopSettingsForm::on_favBtnCols_textChanged(const QString &arg1)
{
    entity()->setFavBtnCols(arg1.toInt());
    drawButtons();
}

void ShopSettingsForm::on_favBtnRows_textChanged(const QString &arg1)
{
    entity()->setFavBtnRows(arg1.toInt());
    drawButtons();
}

void ShopSettingsForm::on_favBtnSize_textChanged(const QString &arg1)
{
    entity()->setFavBtnSize(arg1.toInt());
    drawButtons();
}

FavButton::FavButton(QWidget *parent) : QToolButton(parent)
{
}

void FavButton::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}

void FavButton::dropEvent(QDropEvent *)
{
    emit itemDropped();
}
