#include "PresenterView.h"
#include <QVBoxLayout>
#include <QFormLayout>
#include <QMessageBox>
#include <QHeaderView>

PresenterView::PresenterView(PresenterModel* model, QWidget* parent) : QWidget{ parent }, model{ model }
{
    this->initGUI();
    this->view->setModel(model);
    this->connectSignalsAndSlots();
}

PresenterView::~PresenterView()
{

}

void PresenterView::initGUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout{ this };
    this->setLayout(mainLayout);

    this->view = new QTableView{};
    mainLayout->addWidget(this->view);

    this->idEdit = new QLineEdit{};
    auto validator = new QIntValidator{};
    validator->setBottom(0);
    this->idEdit->setValidator(validator);
    this->textEdit = new QLineEdit{};
    this->answerEdit = new QLineEdit{};
    this->scoreEdit = new QLineEdit{};
    this->scoreEdit->setValidator(validator);
    this->addButton = new QPushButton{ "Add" };

    QFormLayout* formLayout = new QFormLayout{};
    formLayout->addRow("Id", this->idEdit);
    formLayout->addRow("Text", this->textEdit);
    formLayout->addRow("Answer", this->answerEdit);
    formLayout->addRow("Score", this->scoreEdit);
    formLayout->addWidget(this->addButton);

    mainLayout->addLayout(formLayout);
    this->view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    this->setMinimumWidth(1000);
    this->setWindowTitle("Presenter");
}

void PresenterView::connectSignalsAndSlots()
{
    QObject::connect(this->addButton, &QPushButton::clicked, this, [&](){
        if(this->idEdit->text().isEmpty() || this->textEdit->text().isEmpty() || this->answerEdit->text().isEmpty() || this->scoreEdit->text().isEmpty())
        {
            QMessageBox::critical(this, "Error", "All fields must be filled!");
            return;
        }
        int id = this->idEdit->text().toInt();
        std::string text = this->textEdit->text().toStdString();
        std::string answer = this->answerEdit->text().toStdString();
        int score = this->scoreEdit->text().toInt();
        Question q{ id, text, answer, score };
        try{
            this->model->addQuestion(q);
        }
        catch (std::exception& e)
        {
            QMessageBox::critical(this, "Error", e.what());
        }
    });
}

