#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "check/check.h"
#include "goods/goods.h"
#include "outputdialog.h"
#include "settingsdialog.h"
#include <iostream>
#include <QFileDialog>
#include "image/checkimage.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
    this->setupStoresList();
}

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

void MainWindow::setupStoresList() {
    parser = *(new Parser());

    std::vector<std::string> modules_names = parser.search_modules();

    for (std::string name : modules_names) {
        StoreModule m(name);
        std::wstring module_name = m.get_name();

        QString s = QString::fromStdWString(module_name);
        ui->storeType->addItem(s);
    }

#ifdef DEBUG
    for (auto module : parser.search_modules()) {
        std::cout << "Module: " << module << std::endl;
    }
#endif
}

void MainWindow::on_checkType_currentIndexChanged(int index) {
    ui->inputHolder->setCurrentIndex(index);
}

void MainWindow::on_parseButton_clicked() {
    QString s;
    switch (ui->checkType->currentIndex()) {
    case 0:
        s = ui->checkContent->toPlainText();
        break;
    case 1:
        s = ui->checkContentFromImage->toPlainText();
        break;
    }

    std::wstring check_plaintext = s.toStdWString();
    parser.set_module(parser.search_modules()[0]);

    std::vector<Goods> c = parser.parse(check_plaintext);

    if (c.size() == 0) {
        std::cerr << "An error has occured. Check was matched incorrectly. Vector sizes are different" << std::endl;
        return;
    }

    Check check;

    for (auto& g : c) {
        check.add_goods(g);
    }

    OutputDialog d = OutputDialog(this, check);
    d.show();
    d.exec();
}

void MainWindow::on_storeType_currentIndexChanged(int index) {
    std::string module = parser.search_modules()[index];
    parser.set_module(module);
}

void MainWindow::on_chooseImageButton_clicked() {
    QString filename = QFileDialog::getOpenFileName();
    std::cout << filename.toStdString() << std::endl;

    // this->options.set_path(filename.toStdString());
    std::string new_text = "Path to export: " + filename.toStdString();
    ui->pathLabel->setText(QString::fromStdString(new_text));

    CheckImage i(filename.toStdString());
    std::string parsed = i.parse_text();

    ui->checkContentFromImage->setPlainText(QString::fromStdString(parsed));
}


void MainWindow::on_preferencesButton_clicked() {
    SettingsDialog s = SettingsDialog();
    s.show();
    s.exec();
}

