#include "FormSelectLanguage.h"
#include "ui_FormSelectLanguage.h"

#include <QDir>
#include <QDebug>
#include <QRegExp>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonValue>

#include "config_ulcc.h"
#include "ManagerLanguage.h"

FormSelectLanguage::FormSelectLanguage(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FormSelectLanguage)
{
    ui->setupUi(this);
    this->setFixedSize(this->width(),this->height());
    this->setWindowTitle(tr("Select language"));
    this->setWindowIcon(QIcon(QString(GLOBAL_PATH_USERDATA)+"/images/icons/ulcc.png"));

    ManagerLanguage mngLanguage;

    // open ini user config
    QDir dirConfig(QDir::homePath()+"/.ulcc/");
    if (dirConfig.exists()==false) dirConfig.mkpath(QDir::homePath()+"/.ulcc/");

    confSettings = new QSettings(dirConfig.absoluteFilePath("settings.ini"), QSettings::IniFormat);
    confSettings->setPath(QSettings::IniFormat, QSettings::UserScope, QDir::currentPath());

    ui->comboBox_2->clear();
    QDir dirLang(QString(GLOBAL_PATH_USERDATA)+"/langs/");
    dirLang.setFilter(QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot);
    QFileInfoList listLang = dirLang.entryInfoList();
    for (int i = 0; i < listLang.size(); ++i) {
        QFileInfo fileInfo = listLang.at(i);
        QRegExp rx("(ulcc_)(.*)(.qm)");
        if (rx.indexIn(fileInfo.fileName())!=-1){
            QString lang_code = rx.cap(2);
            QString languageName = mngLanguage.getNativeName(lang_code);

            ui->comboBox_2->addItem(languageName,lang_code);
            if (confSettings->value("ulcc/language",QLocale::system().bcp47Name()).toString()==lang_code){
                ui->comboBox_2->setCurrentIndex(ui->comboBox_2->count()-1);
            }
        }
    }

    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(close()));
    connect(ui->pushButton_2,SIGNAL(clicked(bool)),this,SLOT(saveLanguageAbc()));
}

FormSelectLanguage::~FormSelectLanguage(){
    delete ui;
}

void FormSelectLanguage::saveLanguageAbc(){
    confSettings->setValue("ulcc/language",ui->comboBox_2->currentData());
    accept();
}
