#include "paydvouchersdialog.h"
#include "ui_paydvouchersdialog.h"

#include <QFileDialog>

#include "receiptgenerator.h"
#include "shopservice.h"

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

    m_voucherModel = new AutoTableModel<Voucher>(this);
    m_itemModel = new AutoTableModel<VoucherItem>(this);

    ui->tableVouchers->setModel(m_voucherModel);
    ui->tableItems->setModel(m_itemModel);

    ShopService srv;
    m_voucherModel->setData(srv.paiedVouchers());

    connect(ui->tableVouchers->selectionModel(), &QItemSelectionModel::currentRowChanged, [this, &srv](const QModelIndex &current, const QModelIndex &) {
        QSharedPointer<Voucher> voucher = m_voucherModel->itemFromIndex(current);
        srv.loadItems(voucher);
        m_itemModel->setData(voucher->items());
        ui->total->setText(QString::number(voucher->totalPrice().toDouble(), 'f', 2));

        ui->btnPrint->setEnabled(true);
        ui->btnSave->setEnabled(true);
    });
}

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

void PaydVouchersDialog::on_btnPrint_clicked()
{
    QSharedPointer<Voucher> voucher = m_voucherModel->itemFromIndex(ui->tableVouchers->currentIndex());

    ReceiptGenerator generator;
    generator.setVoucher(voucher);
    generator.print();
}

void PaydVouchersDialog::on_btnSave_clicked()
{
    QString fileToSave = QFileDialog::getSaveFileName(this, tr("Save receipt"), "", tr("Text files (*.txt)"));
    QSharedPointer<Voucher> voucher = m_voucherModel->itemFromIndex(ui->tableVouchers->currentIndex());

    if (!fileToSave.isEmpty())
    {
        ReceiptGenerator generator;
        generator.setVoucher(voucher);
        generator.setOutputFile(fileToSave);
        generator.save();
    }
}
