/*
Copyright (c) 2006-2009, Tom Thielicke IT Solutions

SPDX-License-Identifier: GPL-2.0-only
*/

/****************************************************************
**
** Implementation of the LessonDialog class
** File name: lessondialog.cpp
**
****************************************************************/

#include <QFileDialog>
#include <QFontDialog>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QSqlQuery>
#include <QString>
#include <QVBoxLayout>

#include "def/defines.h"
#include "errormessage.h"
#include "lessondialog.h"
#include "sql/startsql.h"

LessonDialog::LessonDialog(QString lessonid, QStringList* data, QWidget* parent)
    : QDialog(parent)
    , currentLessonId(lessonid)
    , lessonData(data)
{
    setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);

    // Create buttons
    createButtons();

    // Create controls
    createControls();

    // Set the layout of all widgets created above
    createLayout();

    // Widget connections
    connect(buttonSave, &QPushButton::clicked, this, &LessonDialog::clickSave);
    connect(buttonCancel, &QPushButton::clicked, this, &LessonDialog::reject);
    connect(buttonHelp, &QPushButton::clicked, this, &LessonDialog::showHelp);

    setMinimumSize(420, 470);

    buttonSave->setFocus();

    updateContent();
}

void LessonDialog::updateContent()
{
    // Dialog is in edit modus (lesson id exist)
    if (currentLessonId == "-1") {
        // New lesson
        lineLessonName->selectAll();
        lineLessonName->setFocus();
    } else {
        if (currentLessonId == "-2") {
            // Import lesson
            lineLessonName->setText(lessonData->at(0).left(20));
            lineLessonDescription->setText("");
            lessonData->removeFirst();
            lineLessonContent->setText(lessonData->join("\n"));

            // Split lesson content to lines
            *lessonData = lineLessonContent->toPlainText().split(
                "\n", Qt::SkipEmptyParts);
            // Delete empty lines
            for (int i = 0; i < lessonData->size(); i++) {
                if (QString(lessonData->at(i).toLocal8Bit().constData())
                        .simplified()
                    == "") {
                    lessonData->removeAt(i);
                }
            }
            lineLessonContent->setText(lessonData->join("\n"));
        } else {
            // Edit lesson
            auto* startSql = new StartSql();
            if (!startSql->getOwnLesson(currentLessonId, lineLessonName,
                    lineLessonDescription, lineLessonContent, radioUnitSentence,
                    radioUnitWord)) {
                // No selected lesson found in combo box
                // -> error message
                ErrorMessage* errorMessage = new ErrorMessage(this);
                errorMessage->showMessage(Error::user_lesson_get,
                    ErrorMessage::Type::Info, ErrorMessage::Cancel::Operation);
                return;
            }
        }
    }
}

void LessonDialog::createButtons()
{
    // Buttons
    buttonCancel = new QPushButton(tr("&Cancel"));
    buttonSave = new QPushButton(tr("&Save"));
    buttonHelp = new QPushButton(tr("&Help"));
    buttonSave->setDefault(true);
}

void LessonDialog::createControls()
{
    // Labels
    labelLessonName
        = new QLabel(tr("Name of the lesson (20 characters max.):"));
    labelLessonDescription
        = new QLabel(tr("Short description (120 characters max.):"));
    labelLessonContent = new QLabel(tr("Lesson content (at least two lines):"));
    labelLessonNotices = new QLabel(
        tr("<u>Explanation:</u><br>&nbsp;<br>Every line (separated by Enter "
           "key) is equivalent to a unit of the lesson. There are two types of "
           "lesson dictation:<br>&nbsp;<br><b>Sentence Lesson</b> - every line "
           "(sentence) will be dictated exactly how it was entered here with a "
           "line break at the end.<br>&nbsp;<br><b>Word Lesson</b> - the lines "
           "will be separated by blanks and a line break passes automatically "
           "after at least %1 characters.")
            .arg(QString::number(t10::num_token_until_new_line)));
    labelLessonNotices->setWordWrap(true);
    labelLessonNotices->setMaximumWidth(180);
    labelLessonUnit = new QLabel(tr(
        "<b>What happens when \"Intelligence\" is enabled?</b><br>With enabled "
        "intelligence, the lines to be dictated will be selected depending on "
        "the typing mistake quotas instead of dictating them in the right "
        "order. Enabling the \"Intelligence\" only makes sense if the lesson "
        "consists of many lines (often \"Word Lessons\").<br>"));
    labelLessonUnit->setWordWrap(true);
    labelLessonUnit->setMaximumWidth(180);
    labelLessonUnitRadio = new QLabel(tr("Dictate the text as:"));
    labelLessonUnitRadio->setWordWrap(true);
    // Lines (text input)
    lineLessonName = new QLineEdit();
    lineLessonName->setMaxLength(20);
    lineLessonDescription = new QLineEdit();
    lineLessonDescription->setMaxLength(120);
    lineLessonContent = new QTextEdit();
    lineLessonContent->setLineWrapMode(QTextEdit::NoWrap);
    lineLessonContent->setAcceptRichText(false);
    // Radiobutton sentence unit
    radioUnitSentence = new QRadioButton(tr("Sentence Lesson"));
    radioUnitSentence->setToolTip(
        tr("Every line will be completed with\na line break at the end"));
    radioUnitSentence->setChecked(true);
    // Radiobutton word unit
    radioUnitWord = new QRadioButton(tr("Word Lesson"));
    radioUnitWord->setToolTip(
        tr("Every unit (line) will be separated\nby blanks. A line break "
           "passes\nautomatically after at least %1 characters.")
            .arg(QString::number(t10::num_token_until_new_line)));
    radioUnitWord->setChecked(false);

    // Dialog is in edit modus (lesson id exist)
    if (currentLessonId != "-1" && currentLessonId != "-2") {
        setWindowTitle(tr("Edit own Lesson"));
        // Change text of lesson name label
        labelLessonName->setText(tr("Name of the Lesson:"));
        // Disable text field "Name of lesson"
        lineLessonName->setEnabled(false);
    } else {
        setWindowTitle(tr("Create own Lesson"));
        // Select text field "Name of lesson"
        // lineLessonName->selectAll();
        // lineLessonName->setCursorPosition(0);
    }
}

void LessonDialog::createLayout()
{
    // Button layout horizontal
    QHBoxLayout* buttonLayoutHorizontal = new QHBoxLayout;
    buttonLayoutHorizontal->addStretch(1);
    buttonLayoutHorizontal->addWidget(buttonCancel);
    buttonLayoutHorizontal->addSpacing(10);
    buttonLayoutHorizontal->addWidget(buttonHelp);
    buttonLayoutHorizontal->addWidget(buttonSave);
    // Group layout vertical
    QHBoxLayout* boxesLayout = new QHBoxLayout;
    boxesLayout->addStretch(1);
    boxesLayout->addWidget(radioUnitSentence);
    boxesLayout->addSpacing(30);
    boxesLayout->addWidget(radioUnitWord);
    boxesLayout->addStretch(1);
    QVBoxLayout* helpLayout = new QVBoxLayout;
    helpLayout->addWidget(labelLessonNotices);
    helpLayout->addSpacing(14);
    helpLayout->addWidget(labelLessonUnit);
    helpLayout->addStretch(1);
    QVBoxLayout* controlLayout = new QVBoxLayout;
    controlLayout->addWidget(labelLessonName);
    controlLayout->addWidget(lineLessonName);
    controlLayout->addSpacing(10);
    controlLayout->addWidget(labelLessonDescription);
    controlLayout->addWidget(lineLessonDescription);
    controlLayout->addSpacing(10);
    controlLayout->addWidget(labelLessonContent);
    controlLayout->addWidget(lineLessonContent);
    controlLayout->addSpacing(10);
    controlLayout->addWidget(labelLessonUnitRadio);
    controlLayout->addLayout(boxesLayout);
    // Full layout of all widgets vertical
    QHBoxLayout* preLayout = new QHBoxLayout;
    preLayout->addLayout(controlLayout);
    preLayout->addSpacing(20);
    preLayout->addLayout(helpLayout);
    // Full layout of all widgets vertical
    QVBoxLayout* mainLayout = new QVBoxLayout;
    mainLayout->addLayout(preLayout);
    mainLayout->addSpacing(1);
    mainLayout->addLayout(buttonLayoutHorizontal);
    mainLayout->setSpacing(5);
    // Pass layout to parent widget (this)
    this->setLayout(mainLayout);
}

void LessonDialog::clickSave()
{
    // Check whether lesson name is filled out
    if (lineLessonName->text() == "") {
        QMessageBox::information(
            this, t10::app_name, tr("Please enter the name of the lesson\n"));
        return;
    }
    // Check whether lesson content is filled out
    if (lineLessonContent->toPlainText() == "") {
        QMessageBox::information(
            this, t10::app_name, tr("Please enter entire lesson content\n"));
        return;
    }

    // Split lesson content to lines
    QStringList contentList
        = lineLessonContent->toPlainText().split("\n", Qt::SkipEmptyParts);
    // Delete empty lines
    for (int i = 0; i < contentList.size(); i++) {
        if (QString(contentList.at(i).toLocal8Bit().constData()).simplified()
            == "") {
            contentList.removeAt(i);
        }
    }
    // Check whether there is enough lesson content
    if (contentList.size() < 2) {
        QMessageBox::information(this, t10::app_name,
            tr("Please enter at least two lines of text\n"));
        return;
    }
    // Check whether there is too much lesson content
    if (contentList.size() > 400) {
        QMessageBox::information(this, t10::app_name,
            tr("Please enter 400 lines of text maximum\n"));
        return;
    }
    // Save the lesson
    auto* startSql = new StartSql();
    if ((currentLessonId == "-1" || currentLessonId == "-2")
        && startSql->ownLessonExist(lineLessonName->text())) {
        QMessageBox::information(this, t10::app_name,
            tr("The name of the lesson already exists. Please enter a new "
               "lesson name.\n"));
        return;
    }
    int lessonUnit = 0;
    if (radioUnitWord->isChecked()) {
        lessonUnit = 1;
    }
    if (!startSql->updateOwnLesson(currentLessonId, lineLessonName->text(),
            lineLessonDescription->text(), contentList, lessonUnit)) {
        // No selected lesson found in combo box
        // -> error message
        ErrorMessage* errorMessage = new ErrorMessage(this);
        errorMessage->showMessage(Error::user_lesson_add,
            ErrorMessage::Type::Info, ErrorMessage::Cancel::Operation);
        return;
    }
    if (!startSql->analyzeOwnLessons()) {
        // No selected lesson found in combo box
        // -> error message
        ErrorMessage* errorMessage = new ErrorMessage(this);
        errorMessage->showMessage(Error::user_lesson_analyze,
            ErrorMessage::Type::Info, ErrorMessage::Cancel::Operation);
        return;
    }
    this->accept();
}

void LessonDialog::showHelp()
{
    helpBrowser = new HelpBrowser("lessons.html#ownlesson", this);
    helpBrowser->show();
}
