#include "addproductdialog.h"

#include "ui_addproductdialog.h"

#include "../colouredlineedit/colouredlineedit.h"

#include "../sqlscript/sqlscript.h"

#include "../integervalidator/integervalidator.h"

#include <QSqlDatabase>

#include <QSqlTableModel>

#include <QDebug>

AddProductDialog::AddProductDialog(QWidget *parent)
    : QDialog(parent), m_ui(new Ui::AddProductDialog) {
  m_ui->setupUi(this);
  setWindowTitle(tr("Product addition"));
  createWidgets();
  configureWidgets();
  setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
}

AddProductDialog::~AddProductDialog() { delete m_ui; }

void AddProductDialog::createWidgets() {
  m_nameLineEdit = new ColouredLineEdit;
  m_ui->m_nameLineEditLayout->addWidget(m_nameLineEdit);
  m_ui->nameLabel->setBuddy(m_nameLineEdit);

  m_barcodeLineEdit = new ColouredLineEdit;
  m_ui->m_barcodeLineEditLayout->addWidget(m_barcodeLineEdit);
  m_ui->barcodeLabel->setBuddy(m_barcodeLineEdit);
}

void AddProductDialog::configureWidgets() {
  CREATE_NAME(viewName, VIEW::AvailableProductTypes);
  auto tableModel = new QSqlTableModel(this, QSqlDatabase::database());
  tableModel->setTable(viewName);
  tableModel->select();
  m_ui->m_productType->setModel(tableModel);

  CREATE_INDEX(nameIndex, COLUMN::AvailableProductTypes_Name);
  m_ui->m_productType->setModelColumn(nameIndex);

  m_barcodeLineEdit->setMaxLength(13);
  m_barcodeLineEdit->setValidator(new IntegerValidator(m_barcodeLineEdit));
}

int AddProductDialog::insertedId() { return m_insertedId; }

void AddProductDialog::done(int resultCode) {
  if (QDialog::Accepted == resultCode) {
    QString nameText = m_nameLineEdit->text();
    QString barcodeText = m_barcodeLineEdit->text();

    bool existName = SqlScript::doesProductExist(nameText);
    bool badName = nameText.isEmpty() || existName;
    if (badName)
      m_nameLineEdit->notice(QColor(Qt::red));

    int length = barcodeText.length();
    long long barcode = barcodeText.toLongLong();
    bool badBarcode = length != 13 || SqlScript::doesBarcodeExist(barcode);
    if (badBarcode)
      m_barcodeLineEdit->notice(QColor(Qt::red));

    if (badName || badBarcode)
      return;

    auto *productType = m_ui->m_productType;
    int row = productType->currentIndex();
    if (row < 0)
      return;

    CREATE_INDEX(idIndex, COLUMN::AvailableProductTypes_Id);
    auto *model = productType->model();
    int productTypeId = model->index(row, idIndex).data().toUInt();
    m_insertedId = SqlScript::insertProduct(nameText, productTypeId,
                                            barcodeText.toLongLong());
    auto *list = m_ui->m_properties;
    int end = list->count();
    for (int index = 0; index != end; ++index)
      if (list->item(index)->checkState() == Qt::CheckState::Checked)
        SqlScript::insertProductAttribute(m_insertedId,
                                          index + 1 /*to order number*/);
  }
  QDialog::done(resultCode);
  return;
}
