#include "camp-odb.hxx"
#include "campsettingsform.h"
#include "ui_campsettingsform.h"

#include <settingsservice.h>
#include <QScroller>
#include <QMessageBox>

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

    m_personPriceModel = new AutoTableModel<PersonPrice>();
    m_personPriceModel->setEditableCols(QList<int>() << 0 << 1 << 2 << 3);
    m_saleModel = new AutoTableModel<Sale>();
    m_saleModel->setEditableCols(QList<int>() << 0 << 1 << 2);

    ui->tablePersonPrices->setModel(m_personPriceModel);
    ui->tableSales->setModel(m_saleModel);

    ui->tablePersonPrices->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->tableSales->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);

    QScroller::grabGesture(ui->tablePersonPrices, QScroller::LeftMouseButtonGesture);
    QScroller::grabGesture(ui->tableSales, QScroller::LeftMouseButtonGesture);

    connect(ui->tablePersonPrices->selectionModel(), &QItemSelectionModel::currentRowChanged, [this](){
        ui->btnPriceDisable->setEnabled(ui->tablePersonPrices->currentIndex().isValid());
        ui->btnPriceRemove->setEnabled(ui->tablePersonPrices->currentIndex().isValid());
        ui->btnPriceDisable->setChecked(m_personPriceModel->itemFromIndex(ui->tablePersonPrices->currentIndex())->active());
    });

    connect(ui->tableSales->selectionModel(), &QItemSelectionModel::currentRowChanged, [this](){
        ui->btnSaleRemove->setEnabled(ui->tableSales->currentIndex().isValid());
    });

    registerBinding(ui->accFee);
    registerBinding(ui->accFeeStartAge);
    registerBinding(ui->accFeeEndAge);
    registerBinding(ui->decimalPlaces);
    registerBinding(ui->accFeeText);
    QList<ComboData> roundings ;
    roundings << ComboData(Enums::R_NONE, tr("None"))
       << ComboData(Enums::R_UP, tr("Up"))
       << ComboData(Enums::R_DOWN, tr("Down"))
       << ComboData(Enums::R_MATH, tr("Mathematic"));
    registerBinding(ui->rounding, roundings);
}

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

bool CampSettingsForm::saveRecord()
{
    bindToData();
    SettingsService srv("CAMP");
    srv.saveSettings(entity());

    Service<PersonPrice> personSrv;
    Service<Sale> saleSrv;
    bool ret = true;

    connect(&personSrv, &IService::dbErrorDelete, [&ret, this](QString){
        QMessageBox::critical(this, tr("Cannot delete"), tr("Price already used"));
        ret = false;
    });

    foreach (PersonPricePtr p, personSrv.all()) {
        bool found = false;
        foreach (PersonPricePtr price, m_personPriceModel->list()) {
            if (price->id() == p->id())
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            personSrv.erase(p);
        }
    }

    foreach (PersonPricePtr p, m_personPriceModel->list()) {
        bool found = false;
        foreach (PersonPricePtr price, personSrv.all()) {
            if (price->id() == p->id())
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            personSrv.save(p);
        }
        else
        {
            personSrv.update(p);
        }
    }

    foreach (SalePtr s, saleSrv.all()) {
        saleSrv.erase(s);
    }

    foreach (SalePtr s, m_saleModel->list()) {
        saleSrv.save(s);
    }

    return ret;
}

void CampSettingsForm::loadEntity()
{
    SettingsService srv("CAMP");
    CampSettingsPtr settings = srv.loadSettings<CampSettings>();
    setEntity(settings);

    Service<PersonPrice> personSrv;
    Service<Sale> saleSrv;

    m_personPriceModel->setData(personSrv.all());
    m_saleModel->setData(saleSrv.all());

    ui->btnPriceDisable->setEnabled(false);
    ui->btnPriceRemove->setEnabled(false);
    ui->btnSaleRemove->setEnabled(false);
}

void CampSettingsForm::on_btnPriceAdd_clicked()
{
    PersonPricePtr price(new PersonPrice());
    m_personPriceModel->addRow(price);
}

void CampSettingsForm::on_btnSaleAdd_clicked()
{
    SalePtr sale(new Sale());
    m_saleModel->addRow(sale);
}

void CampSettingsForm::on_btnPriceRemove_clicked()
{
    m_personPriceModel->removeRowAt(ui->tablePersonPrices->currentIndex());
}

void CampSettingsForm::on_btnPriceDisable_clicked()
{
    PersonPricePtr price = m_personPriceModel->itemFromIndex(ui->tablePersonPrices->currentIndex());
    price->setActive(!price->active());
}

void CampSettingsForm::on_btnPriceFilter_clicked()
{
    Service<PersonPrice> srv;
    if (ui->btnPriceFilter->isChecked())
    {
        m_personPriceModel->setData(srv.all("active = 1"));
    }
    else
    {
        m_personPriceModel->setData(srv.all());
    }
}

void CampSettingsForm::on_btnSaleRemove_clicked()
{
    m_saleModel->removeRowAt(ui->tableSales->currentIndex());
}
