/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QtWidgets>
#include <QtGlobal>

#include "CodeTemplateDialog.h"
#include "MvQMethods.h"


CodeTemplateDialog::CodeTemplateDialog(QString& templateListFilePath, QWidget* parent) :
    QDialog(parent)
{
    setupUi(this);  // this sets up GUI


    auto* insertButton = new QPushButton(tr("&Insert Template"));
    insertButton->setDefault(true);
    buttonBox->addButton(insertButton, QDialogButtonBox::ActionRole);


    connect(insertButton, SIGNAL(clicked()), this, SLOT(onInsertButtonClicked()));


    // store the file path

    templateListFilePath_ = templateListFilePath;
}


void CodeTemplateDialog::reloadCodeTemplates(TabsSettings& tabSettings)
{
    // load the template list

    QFile file(templateListFilePath_);

    if (file.open(QFile::ReadOnly | QFile::Text))  // try to open in read-only mode
    {
        int index    = 0;
        QString body = "";
        QTextStream in(&file);
        QString spaces = "";


        // reset our list of code bodies

        templateCodeBodies_.clear();
        templateListWidget->clear();
        previewPlainTextEdit->clear();


        // does the user like spaces instead of tabs? If so, get ready to replace tabs with spaces

        if (tabSettings.useSpacesForTabs) {
            spaces.fill(' ', tabSettings.numSpacesInTab);
        }


        while (!file.atEnd())  // each line in the file is a function name to add to the list
        {
            QListWidgetItem* item;
            QString s = file.readLine();

            // is this the heading of a new template?

            if (s.startsWith("{") && s.endsWith("}\n")) {
                // add the previous template body to our list?
                if (index > 0) {
                    templateCodeBodies_.append(body);
                    body = "";
                }

                QString title = s.mid(1, s.count() - 3);                         // remove the curly brackets and the newline
                item          = new QListWidgetItem(title, templateListWidget);  // create a new item for the tree
                item->setData(Qt::UserRole, index);                              // set the index
                index++;
            }

            else {
                QString bodyline = s;

                if (tabSettings.useSpacesForTabs) {
                    bodyline.replace("\t", spaces);
                }
                body.append(bodyline);
            }
        }


        // add the last template body to our list?

        if (index > 0) {
            templateCodeBodies_.append(body);
            body = "";
        }
    }

    else {
        // could not load the function list file

        QMessageBox::warning(this, tr("Template List"),
                             tr("Cannot read file %1:\n%2.")
                                 .arg(templateListFilePath_)
                                 .arg(file.errorString()));
    }


    // set up a fixed-pitch font for the preview pane
    QFont font = MvQ::findMonospaceFont();
    previewPlainTextEdit->setFont(font);
    QFontMetrics fm(font);

#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
    previewPlainTextEdit->setTabStopDistance(MvQ::textWidth(fm, QLatin1Char(' ')) * tabSettings.numSpacesInTab);
#else
    previewPlainTextEdit->setTabStopWidth(MvQ::textWidth(fm, QLatin1Char(' ')) * tabSettings.numSpacesInTab);
#endif
    previewPlainTextEdit->setLineWrapMode(QPlainTextEdit::NoWrap);  // we don't allow line wrapping


    // set up the signal/slot connections

    //connect (insertButton, SIGNAL(clicked()), this, SLOT(onInsertButtonClicked()));
    //connect (treeWidget,   SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onItemDoubleClicked(QTreeWidgetItem*, int)));
    connect(templateListWidget, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(onItemChanged(QListWidgetItem*, QListWidgetItem*)));
}


// ---------------------------------------------------------------------------
// CodeTemplateDialog::onItemChanged
// triggered when the selected item is changed
// ---------------------------------------------------------------------------

void CodeTemplateDialog::onItemChanged(QListWidgetItem* item, QListWidgetItem* /*previous*/)
{
    //    emit insertFunctionName (item->text(0)); // emit a signal with the function name
    //    close();
    if (item != nullptr) {
        int index = item->data(Qt::UserRole).toInt();
        previewPlainTextEdit->clear();
        previewPlainTextEdit->insertPlainText(templateCodeBodies_.at(index));
    }
}


// ---------------------------------------------------------------------------
// CodeTemplateDialog::onInsertButtonClicked
// triggered when the user clicks the Insert button
// ---------------------------------------------------------------------------

void CodeTemplateDialog::onInsertButtonClicked()
{
    emit insertCodeTemplate(previewPlainTextEdit->toPlainText());  // emit a signal with the code template
    close();
}
