//============================================================================
// Copyright 2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================

#include "PlainTextWidget.h"

#include <QDebug>
#include <QFontDatabase>

PlainTextWidget::PlainTextWidget(QWidget* parent) :
    QWidget(parent)
{
    setupUi(this);

    externalTb_->hide();

    searchLine_->setEditor(textEdit_);
    searchLine_->setVisible(false);

    lineNumberTb_->setChecked(textEdit_->showLineNumbers());

    connect(lineNumberTb_, SIGNAL(clicked(bool)),
            this, SLOT(showLineNumbersClicked(bool)));
}

PlainTextWidget::~PlainTextWidget() = default;

PlainTextEdit* PlainTextWidget::editor() const
{
    return textEdit_;
}

MessageLabel* PlainTextWidget::messageLabel() const
{
    return messageLabel_;
}

void PlainTextWidget::clear()
{
    textEdit_->clear();
    messageLabel_->clear();
    messageLabel_->hide();
}

void PlainTextWidget::removeSpacer()
{
    // Remove the first spcer item!!
    for (int i = 0; horizontalLayout->count(); i++) {
        if (QSpacerItem* sp = horizontalLayout->itemAt(i)->spacerItem()) {
            horizontalLayout->takeAt(i);
            delete sp;
            break;
        }
    }
}

void PlainTextWidget::on_searchTb__clicked()
{
    searchLine_->setVisible(true);
    searchLine_->setFocus();
    searchLine_->selectAll();
}

void PlainTextWidget::on_gotoLineTb__clicked()
{
    textEdit_->gotoLine();
}

void PlainTextWidget::on_fontSizeUpTb__clicked()
{
    // We need to call a custom slot here instead of "zoomIn"!!!
    textEdit_->slotZoomIn();
}

void PlainTextWidget::on_fontSizeDownTb__clicked()
{
    // We need to call a custom slot here instead of "zoomOut"!!!
    textEdit_->slotZoomOut();
}

void PlainTextWidget::showLineNumbersClicked(bool st)
{
    textEdit_->setShowLineNumbers(st);
}

void PlainTextWidget::readSettings(QSettings& settings, QString group)
{
    settings.beginGroup(group);
    if (settings.contains("lineNumbers")) {
        lineNumberTb_->setChecked(settings.value("lineNumbers").toBool());
        showLineNumbersClicked(lineNumberTb_->isChecked());
    }
    settings.endGroup();
}

void PlainTextWidget::writeSettings(QSettings& settings, QString group)
{
    settings.beginGroup(group);
    settings.setValue("lineNumbers", lineNumberTb_->isChecked());
    settings.endGroup();
}
