#include <QSortFilterProxyModel>

#include "receiptloadform.h"
#include "ui_receiptloadform.h"
#include "shopservice.h"
#include "shop-odb.hxx"

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

    m_voucherModel = new AutoTableModel<Voucher>(this);
    ShopService srv;
    m_voucherModel->setData(srv.all(QString("status = %1").arg(QString::number(Voucher::NOT_PAID))));
    m_voucherModel->setTranslations(Context::instance().plugin("SHOP")->translations());
    ui->tabVouchers->setModel(m_voucherModel);
    ui->tabVouchers->setColumnHidden(0, true);
    ui->tabVouchers->setColumnHidden(1, true);
    ui->tabVouchers->setColumnHidden(6, true);
    ui->tabVouchers->setColumnHidden(7, true);
    ui->tabVouchers->setColumnHidden(8, true);
    ui->tabVouchers->setColumnHidden(9, true);
    ui->tabVouchers->setColumnHidden(10, true);
    ui->tabVouchers->setColumnHidden(11, true);
    ui->tabVouchers->setColumnHidden(13, true);
    ui->tabVouchers->setColumnHidden(14, true);
    ui->tabVouchers->setColumnHidden(15, true);
    ui->tabVouchers->setColumnHidden(16, true);
    ui->tabVouchers->setColumnHidden(17, true);
    ui->tabVouchers->setColumnHidden(18, true);
    ui->tabVouchers->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    ui->tabVouchers->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch);
    ui->tabVouchers->horizontalHeader()->setSectionResizeMode(5, QHeaderView::Stretch);

    m_itemModel = new AutoTableModel<VoucherItem>(this);
    m_itemModel->setTranslations(Context::instance().plugin("SHOP")->translations());
    m_itemModel->setCheckboxSelect(true);
    ui->tabItems->setModel(m_itemModel);
    ui->tabItems->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);

    connect(ui->tabVouchers->selectionModel(), &QItemSelectionModel::currentRowChanged, [this](const QModelIndex &current, QModelIndex){
        ShopService srv;
        VoucherPtr voucher = m_voucherModel->itemFromIndex(current);
        srv.loadItems(voucher);
        m_itemModel->setData(voucher->items());
    });
}

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

QList<VoucherItemPtr> ReceiptLoadForm::selectedItems()
{
    return m_itemModel->selectedItems();
}

VoucherPtr ReceiptLoadForm::selectedVoucher()
{
    return m_voucherModel->itemFromIndex(ui->tabVouchers->currentIndex());
}

void ReceiptLoadForm::on_lineEdit_textChanged(const QString &text)
{
    QSortFilterProxyModel proxy;
    proxy.setSourceModel(m_voucherModel);
    proxy.setFilterKeyColumn(3);
    proxy.setFilterCaseSensitivity(Qt::CaseInsensitive);
    proxy.setFilterFixedString(text);

    QModelIndex matchingIndex = proxy.mapToSource(proxy.index(0,0));
    if(matchingIndex.isValid()){
        ui->tabVouchers->scrollTo(matchingIndex, QAbstractItemView::EnsureVisible);
        ui->tabVouchers->setCurrentIndex(matchingIndex);
    }
}
