#include "commoditysettingsform.h"
#include "ui_commoditysettingsform.h"
#include <service.h>
#include "commodity-odb.hxx"

CommoditySettingsForm::CommoditySettingsForm(QWidget *parent) :
    IForm(parent),
    ui(new Ui::CommoditySettingsForm)
{
    ui->setupUi(this);
    m_table = new AutoTableModel<CommodityTypeData>();
    m_table->setEditableCols(QList<int>() << 0);
    ui->commodityTypesTable->setModel(m_table);
}

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

void CommoditySettingsForm::loadEntity()
{
    Service<CommodityTypeData> commodityService;
    m_table->setData(commodityService.all());
}

bool CommoditySettingsForm::saveRecord()
{
    Service<CommodityTypeData> commodityService;
    foreach (QSharedPointer<CommodityTypeData> item, m_table->list())
    {
        if(item->id() == 0)
        {
            commodityService.save(item);
        }
        else
        {
            commodityService.update(item);
        }

    }
    foreach (QSharedPointer<CommodityTypeData> item, m_delCommodityTypes)
    {
        commodityService.erase(item);

    }

    return true;
}

void CommoditySettingsForm::on_addCommodityType_clicked()
{
    m_table->addRow(QSharedPointer<CommodityTypeData>(new CommodityTypeData));
}

void CommoditySettingsForm::on_delCommodityType_clicked()
{
    if(m_table->itemFromIndex(ui->commodityTypesTable->currentIndex())->id() != 0)
    {
        m_delCommodityTypes.append(m_table->itemFromIndex(ui->commodityTypesTable->currentIndex()));
    }
    m_table->removeRowAt(ui->commodityTypesTable->currentIndex());
}
