#include "campwizard.h"
#include "ui_campwizard.h"
#include "campservice.h"
#include "addservicedialog.h"

#include <core.h>
#include <addressbookservice.h>
#include <accservice.h>
#include <reporting/reportviewer.h>

#include <QScroller>

////////////////////////////////////
/// \brief AddressHelper::AddressHelper
/// \param parent
///
AddressHelper::AddressHelper(QObject *parent)
    :QObject(parent)
{
    m_address = AddressbookDataPtr(new AddressbookData);
}

QSharedPointer<QObject> AddressHelper::address() const
{
    return m_address;
}

void AddressHelper::setAddress(const QSharedPointer<QObject> &address)
{
    if (qobject_cast<AddressbookData*>(address.data()) != NULL)
    {
        m_address = qSharedPointerDynamicCast<AddressbookData, QObject>(address);
    }
}

AddressbookDataPtr AddressHelper::addr() const
{
    return m_address;
}

void AddressHelper::setAddr(const AddressbookDataPtr &address)
{
    m_address = address;
}

AddressbookDataPtr AddressHelper::newAddress()
{
    AddressBookService adbSrv;
    m_copyAddress = adbSrv.copyAddress(m_address);

    return m_copyAddress;
}

AddressbookDataPtr AddressHelper::copyAddress()
{
    if (m_copyAddress.isNull())
    {
        m_copyAddress = AddressbookDataPtr(new AddressbookData);
    }

    return m_copyAddress;
}

//////////////////////////////////////////////////////////////
/// \brief SaleHelper::SaleHelper
/// \param parent
///
SaleHelper::SaleHelper(QObject *parent) :QObject(parent)
{
    m_sale = SalePtr(new Sale);
}

SalePtr SaleHelper::salePtr() const
{
    return m_sale;
}

void SaleHelper::setSalePtr(const SalePtr &sale)
{
    m_sale = sale;
}

QSharedPointer<QObject> SaleHelper::sale() const
{
    return m_sale;
}

void SaleHelper::setSale(const QSharedPointer<QObject> &sale)
{
    if (qobject_cast<Sale*>(sale.data()) != NULL)
    {
        m_sale = qSharedPointerDynamicCast<Sale, QObject>(sale);
        emit saleChanged();
    }
}

///////////////////////////////////////////////////////////
/// \brief CampWizard::CampWizard
/// \param parent
///
CampWizard::CampWizard(QWidget *parent) :
    QWizard(parent),
    ui(new Ui::CampWizard)
{
    ui->setupUi(this);

    m_peopleModel = new AutoTableModel<AddressItem>(this);
    m_peopleModel->setTranslations(Context::instance().plugin("CAMP")->translations());
    ui->tablePeople->setModel(m_peopleModel);
    ui->tablePeople->hideColumn(2);
    ui->tablePeople->hideColumn(3);
    ui->tablePeople->hideColumn(4);
    ui->tablePeople->hideColumn(5);
    ui->tablePeople->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->tablePeople->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);

    connect(ui->tablePeople->selectionModel(), &QItemSelectionModel::currentRowChanged, [this](QModelIndex, QModelIndex){
        ui->btnRemove->setEnabled(!m_data->people().isEmpty());
        ui->btnOwner->setEnabled(!m_data->people().isEmpty());
    });

    m_dataBinder = new ObjectBinder(this);
    m_dataBinder->registerBinding(ui->start);
    m_dataBinder->registerBinding(ui->end);
    m_dataBinder->registerBinding(ui->totalPrice);
    m_dataBinder->registerBinding(ui->totalSale);

    m_addrHelper = new AddressHelper(this);

    Service<AddressbookData> addrSrv;
    m_addrHelperBinder = new ObjectBinder(this);
    m_addrHelperBinder->registerBinding(ui->address, ComboData::createComboData(addrSrv.all("", "lastName, firstName")));
    m_addrHelperBinder->setData(m_addrHelper);

    m_addressBinder = new ObjectBinder(this);
    m_addressBinder->registerBinding(ui->title);
    m_addressBinder->registerBinding(ui->firstName);
    m_addressBinder->registerBinding(ui->lastName);
    m_addressBinder->registerBinding(ui->birthDate);
    m_addressBinder->registerBinding(ui->idCardNumber);
    m_addressBinder->registerBinding(ui->ztp);
    m_addressBinder->registerBinding(ui->addressStreet);
    m_addressBinder->registerBinding(ui->addressHouseNumber);
    m_addressBinder->registerBinding(ui->addressZipCode);
    m_addressBinder->registerBinding(ui->addressCity);

    Service<CountryData> coutrySrv;
    m_addressBinder->registerBinding(ui->country, ComboData::createComboData(coutrySrv.all()));

    m_addressBinder->setData(m_addrHelper->copyAddress().data());
    m_addressBinder->bindToUi();

    m_bindAddrCombo = true;

    Service<AccService> serviceSrv;
    m_servicesModel = new AutoTableModel<AccService>(this);
    m_servicesModel->setTranslations(Context::instance().plugin("CAMP")->translations());
    m_servicesModel->setData(serviceSrv.all());
    ui->tableServices->setModel(m_servicesModel);

    ui->tableServices->hideColumn(1);
    ui->tableServices->hideColumn(3);
    ui->tableServices->hideColumn(4);
    ui->tableServices->hideColumn(5);
    ui->tableServices->hideColumn(6);

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

    m_itemsModel = new AutoTableModel<ServiceItem>();
    m_itemsModel->setTranslations(Context::instance().plugin("CAMP")->translations());
    ui->tableItems->setModel(m_itemsModel);

    ui->tableItems->hideColumn(1);
    ui->tableItems->hideColumn(4);
    ui->tableItems->hideColumn(5);
    ui->tableItems->hideColumn(6);
    ui->tableItems->hideColumn(7);

    ui->tableItems->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);

    connect(ui->tableServices->selectionModel(), &QItemSelectionModel::currentRowChanged, [this](QModelIndex current, QModelIndex){
        ui->btnAddService->setEnabled(current.isValid());
    });

    connect(ui->tableItems->selectionModel(), &QItemSelectionModel::currentRowChanged, [this](QModelIndex, QModelIndex){
        ui->btnRemoveService->setEnabled(!m_data->services().isEmpty());
    });

    m_saleHelper = new SaleHelper(this);
    m_saleBinder = new ObjectBinder(this);
    Service<Sale> saleSrv;
    m_saleBinder->registerBinding(ui->sale, ComboData::createComboData(saleSrv.all()));
    m_saleBinder->setData(m_saleHelper);
    m_saleBinder->bindToUi();

    ui->tabPeople->setModel(m_peopleModel);
    ui->tabPeople->hideColumn(0);
    ui->tabPeople->hideColumn(1);
    ui->tabPeople->hideColumn(6);
    ui->tabPeople->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);

    ui->tabServices->setModel(m_itemsModel);
    ui->tabServices->hideColumn(1);
    ui->tabServices->hideColumn(3);
    ui->tabServices->hideColumn(7);
    ui->tabServices->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->tabServices->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);

    QScroller::grabGesture(ui->tabServices, QScroller::LeftMouseButtonGesture);
    QScroller::grabGesture(ui->tabPeople, QScroller::LeftMouseButtonGesture);

    m_newRecord = false;
}

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

void CampWizard::setData(const CampDataPtr &data)
{
    m_data = data;

    m_dataBinder->setData(data.data());
    m_dataBinder->bindToUi();
    m_addrHelperBinder->bindToUi();

    m_peopleModel->setData(data->people());
    m_itemsModel->setData(data->services());

    ui->sale_2->setValue(m_data->sale().toDouble());
    ui->lblSale->setText(m_data->fixedSale() ? tr("Fixed amound") : tr("%"));
}

void CampWizard::on_btnAdd_clicked()
{
    m_addressBinder->bindToData();

    CampService srv;
    AddressBookService adbSrv;

    if (ui->groupNew->isChecked())
    {
        AddressbookDataPtr newAddr = adbSrv.copyAddress(m_addrHelper->copyAddress());
        adbSrv.save(newAddr);
        srv.addPerson(m_data, newAddr);

        m_bindAddrCombo = false;
        m_addrHelperBinder->registerBinding(ui->address, ComboData::createComboData(adbSrv.all()));
        m_addrHelperBinder->bindToUi();
        m_bindAddrCombo = true;
    }
    else
    {
        srv.addPerson(m_data, m_addrHelper->addr());
    }

    m_peopleModel->setData(m_data->people());
}


void CampWizard::on_address_currentIndexChanged(int)
{
    if (m_bindAddrCombo)
    {
        AddressBookService adbSrv;
        m_addrHelperBinder->bindToData();
        m_addressBinder->setData(m_addrHelper->newAddress().data());
        m_addressBinder->bindToUi();
    }
}

void CampWizard::on_btnRemove_clicked()
{
    AddressItemPtr selAddr = m_peopleModel->itemFromIndex(ui->tablePeople->currentIndex());
    m_data->removePerson(selAddr);
    m_peopleModel->setData(m_data->people());

    ui->btnOwner->setEnabled(false);
    ui->btnRemove->setEnabled(false);
}

void CampWizard::on_btnOwner_clicked()
{
    CampService srv;
    AddressItemPtr selAddr = m_peopleModel->itemFromIndex(ui->tablePeople->currentIndex());
    srv.setOwner(m_data, selAddr);

    QModelIndex currIndex = ui->tablePeople->currentIndex();
    m_peopleModel->setData(m_data->people());
    ui->tablePeople->setCurrentIndex(currIndex);
}

void CampWizard::on_groupNew_clicked(bool checked)
{
    if (checked)
    {
        ui->address->setEnabled(false);
    }
    else
    {
        ui->address->setEnabled(true);
    }
}

void CampWizard::on_CampWizard_currentIdChanged(int id)
{
    if (id == 2)
    {
        CampService srv;
        srv.calculate(m_data);

        m_dataBinder->bindToUi();
        m_itemsModel->setData(m_data->services());

        ui->lFrom->setText(m_data->start().toString("d. M. yyyy"));
        ui->lTo->setText(m_data->end().toString("d. M. yyyy"));
        ui->lDays->setText(QString::number(m_data->start().daysTo(m_data->end())));
        ui->lOwner->setText(m_data->ownerAddress());
    }
}

void CampWizard::on_btnAddService_clicked()
{
    AccServicePtr service = m_servicesModel->itemFromIndex(ui->tableServices->currentIndex());
    AddServiceDialog *dialog = new AddServiceDialog(service, this);

    dialog->setAttribute(Qt::WA_DeleteOnClose);

    connect(dialog, &QDialog::accepted, [=](){
        CampService srv;
        srv.addService(m_data, service, dialog->price(), dialog->description());
        m_itemsModel->setData(m_data->services());
    });

    dialog->show();
}

void CampWizard::on_btnRemoveService_clicked()
{
    ServiceItemPtr item = m_itemsModel->itemFromIndex(ui->tableItems->currentIndex());
    m_data->removeServiceItem(item);
    m_itemsModel->setData(m_data->services());

    ui->btnRemoveService->setEnabled(false);
}

void CampWizard::on_checkSale_clicked()
{
    ui->sale->setEnabled(ui->checkSale->isChecked());
    applySale();
}

void CampWizard::applySale()
{
    if (m_data.isNull())
    {
        return;
    }

    if (ui->checkSale->isChecked())
    {
        m_saleBinder->bindToData();
        m_data->setSale(m_saleHelper->salePtr()->sale());
        m_data->setFixedSale(m_saleHelper->salePtr()->fixed());
    }
    else
    {
        m_data->setSale(QDecDouble(0));
    }
}

void CampWizard::on_sale_currentIndexChanged(int)
{
    applySale();
}

void CampWizard::setNewRecord(bool newRecord)
{
    m_newRecord = newRecord;

    if (newRecord)
    {
        ui->wSale->setVisible(false);
        ui->checkSale->setText(tr("Apply sale"));
    }
    else
    {
        ui->wSale->setVisible(true);
        ui->checkSale->setText(tr("Change"));
    }
}

bool CampWizard::validateCurrentPage()
{
    m_dataBinder->bindToData();

    if (currentPage() == ui->peoplePage && m_data->people().isEmpty())
    {
        QMessageBox::critical(this, tr("Error"), tr("Add people."));
        return false;
    }

    if (currentPage() == ui->peoplePage && m_data->start() >= m_data->end())
    {
        QMessageBox::critical(this, tr("Error"), tr("Start date is after or equals end date."));
        return false;
    }

    if (currentPage() == ui->servicePage && m_data->services().isEmpty())
    {
        QMessageBox::critical(this, tr("Error"), tr("Add service."));
        return false;
    }

    return true;
}

void CampWizard::accept()
{
    CampService srv;
    bool success = true;

    connect(&srv, &IService::dbError, [this, &success](QString msg){
        QMessageBox::critical(this, tr("Database error"), tr(msg.toStdString().c_str()));
        success = false;
    });

    connect(&srv, &IService::permissionDenied, [this, &success](QString msg){
        QMessageBox::critical(this, tr("Permission denied"), msg.toStdString().c_str());
        success = false;
    });

    if (m_newRecord && m_data->id() == 0)
    {
        srv.saveCamp(m_data);
    }
    else
    {
        srv.updateCamp(m_data);
    }

    if (success)
    {
        QDialog::accept();
    }
}

void CampWizard::on_btnPrint_clicked()
{
    if (QMessageBox::question(this, tr("Save record?"), tr("Record must be saved before print. Do you want to save record?")) != QMessageBox::Yes)
    {
        return;
    }

    CampService srv;
    bool success = true;

    connect(&srv, &IService::dbError, [this, &success](QString msg){
        QMessageBox::critical(this, tr("Database error"), tr(msg.toStdString().c_str()));
        success = false;
    });

    connect(&srv, &IService::permissionDenied, [this, &success](QString msg){
        QMessageBox::critical(this, tr("Permission denied"), msg.toStdString().c_str());
        success = false;
    });

    if (m_newRecord && m_data->id() == 0)
    {
        srv.saveCamp(m_data);
    }
    else
    {
        srv.updateCamp(m_data);
    }

    if(!success)
    {
        return;
    }

    ReportPtr report(new Report);
    report->setFile("camp_accommodation_document.lrxml");

    VariableFiller filler;
    filler.fill(report, m_data->id());

    ReportViewer *viewer = new ReportViewer(this);
    viewer->setAttribute(Qt::WA_DeleteOnClose);
    viewer->setReport(report);
    viewer->openPreview();

    connect(viewer, &QDialog::finished, [this](int){
       this->accept();
    });
}
