#include "dialogsettings.h"
#include "ui_dialogsettings.h"
#include "tools.h"
#include <QFile>
#include <QXmlStreamReader>
#include <QRegExpValidator>

DialogSettings::DialogSettings(ConnectorToServer* connectorToServer, bool instructorIsLogged, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogSettings),
    settings(nullptr),
    connectorToServer(nullptr),
    flSettingsServerChanged(false)
{
    ui->setupUi(this);

    ui->btnUpdateStyle->setObjectName("btnUpdateStyle");
    ui->btnSetVersion->setObjectName("btnSetVersion");
    ui->btnSave->setObjectName("btnSave");
    ui->checkAutoStart->setObjectName("checkAutoStart");

#ifndef PROJECT_TYPE_DEBUG
    ui->btnUpdateStyle->setVisible(false);
#endif

    this->connectorToServer = connectorToServer;

    /* Создаем строку для регулярного выражения */
    QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])";
    /* Создаем регулярное выражение с применением строки, как
     * повторяющегося элемента
     */
    QRegExp ipRegex ("^" + ipRange
                     + "\\." + ipRange
                     + "\\." + ipRange
                     + "\\." + ipRange + "$");
    /* Создаем Валидатор регулярного выражения с применением
     * созданного регулярного выражения
     */
    QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this);
    /* Устанавливаем Валидатор на QLineEdit */
    ui->editAddress->setValidator(ipValidator);

    settings = new ServerSettings;

    //Задаём два пункта с текстом локалей в комбобоксе
    ui->cmbLanguage->addItems(QStringList() << "English" << "Русский");

    if(loadSettings(settings))
    {
        if(settings->Language == "ENG")
            ui->cmbLanguage->setCurrentText("English");
        else
            ui->cmbLanguage->setCurrentText("Русский");

        ui->editAddress->setText(settings->Address);
        ui->editPort->setText(settings->Port);
        ui->checkAutoStart->setChecked(settings->isAutoStart);
    }

    ui->btnSetVersion->setEnabled(false);
    if(connectorToServer)
        if(connectorToServer->getIsConnected())
        {
            if(instructorIsLogged)
                ui->btnSetVersion->setEnabled(true);
        }

    ui->label_AutoStart->setVisible(false);
    ui->checkAutoStart->setVisible(false);

    ui->btnSave->setEnabled(false);
    flSettingsServerChanged = false;
}

DialogSettings::~DialogSettings()
{
    delete ui;
    delete settings;
}

ServerSettings DialogSettings::getSettings()
{
    return *settings;
}

void DialogSettings::changeEvent(QEvent *event)
{
    // В случае получения события изменения языка приложения
    if (event->type() == QEvent::LanguageChange)
    {// переведём окно заново
        ui->retranslateUi(this);
    }
}

void DialogSettings::on_btnUpdateStyle_clicked()
{
    emit signal_UpdateStyleSheet();
}

bool DialogSettings::loadSettings(ServerSettings *settings)
{
    QFile file(settingsName);
    if(! file.open(QIODevice::ReadOnly))
        return false;

    QXmlStreamReader xmlReader(&file);

    while (!xmlReader.atEnd()){

        if(xmlReader.isStartElement()){

            if(xmlReader.name() == "ServerSettings")
            {

                foreach(const QXmlStreamAttribute &attr, xmlReader.attributes()){
                    QString name = attr.name().toString();
                    QString value = attr.value().toString();

                    if(name == "Address"){
                        settings->Address = value;
                    }

                    if(name == "Port"){
                        settings->Port = value;
                    }

                    if(name == "Language"){
                        settings->Language = value;
                    }

                    if(name == "AutoStart"){
                        settings->isAutoStart = value.toInt();
                    }

                }
            }
        }

        xmlReader.readNext();
    }

    file.close();

    return true;
}

bool DialogSettings::saveSettings()
{
    QFile file(settingsName);

    if(! file.open(QIODevice::WriteOnly))
        return false;

    QXmlStreamWriter xmlWriter(&file);

    xmlWriter.setAutoFormatting(true);
    xmlWriter.writeStartDocument();

    xmlWriter.writeStartElement("ServerSettingsContainer");
    xmlWriter.writeStartElement("ServerSettings");

    xmlWriter.writeAttribute("Address", settings->Address);
    xmlWriter.writeAttribute("Port", settings->Port);
    xmlWriter.writeAttribute("Language", settings->Language);
    xmlWriter.writeAttribute("AutoStart", QString::number(settings->isAutoStart));

    xmlWriter.writeEndElement();
    xmlWriter.writeEndElement();

    xmlWriter.writeEndDocument();

    file.close();

    return true;
}

void DialogSettings::on_btnSave_clicked()
{
    if(ui->cmbLanguage->currentText() == QStringLiteral("English"))
    {
        settings->Language = "ENG";
    }
    else
    {
        settings->Language = "RUS";
    }

    settings->Address = ui->editAddress->text();
    settings->Port = ui->editPort->text();
    settings->isAutoStart = ui->checkAutoStart->isChecked();

    saveSettings();

    this->accept();
}

void DialogSettings::on_btnSetVersion_clicked()
{
    if(connectorToServer)
        if(connectorToServer->getIsConnected())
            connectorToServer->sendShowVersionSelect();
}

void DialogSettings::on_cmbLanguage_currentIndexChanged(int index)
{
    ui->btnSave->setEnabled(true);
}

void DialogSettings::on_editAddress_textChanged(const QString &arg1)
{
    ui->btnSave->setEnabled(true);
    flSettingsServerChanged = true;
}

void DialogSettings::on_editPort_textChanged(const QString &arg1)
{
    ui->btnSave->setEnabled(true);
    flSettingsServerChanged = true;
}

void DialogSettings::on_DialogSettings_accepted()
{
    QString language;

    if(settings->Language == "ENG")
        language = QString("en_EN");
    else
        language = QString("ru_RU");

    emit signal_LanguageChanged(language);
}
