#include "ManagerLanguage.h"

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

#include "config_ulcc.h"

ManagerLanguage::ManagerLanguage(){
    QFile file;
    file.setFileName(QString(GLOBAL_PATH_USERDATA)+"/langs/langs.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << tr("Error while opening")+" langs.json" << file.errorString();
    }else{
        QByteArray val = file.readAll();
        file.close();

        QJsonDocument document = QJsonDocument::fromJson(val);
        if (document.isEmpty()){
            qDebug() << "langs.json "+tr("is not valid");
        }else{
            rootLangs = document.object();
        }
    }

}

QString ManagerLanguage::getNativeName(QString lang_code){
    QString languageName="";

    QString lang_code_loc = lang_code;
    if (lang_code_loc.indexOf("_")==-1) lang_code_loc+="_"+lang_code_loc.toUpper();

    if (!rootLangs.value(lang_code).toObject().value("nativeName").isNull()==true){
        languageName = rootLangs.value(lang_code).toObject().value("nativeName").toString();

    }

    if (languageName.isEmpty()){
        QLocale loc(lang_code_loc);
        languageName = loc.nativeLanguageName();
        if (languageName.isEmpty()) languageName= QLocale::languageToString(loc.language());
    }

    if (!languageName.isEmpty()) languageName[0]=languageName[0].toUpper();

    if (languageName.isEmpty() or languageName=="C"){
            languageName=lang_code;
    }


    return languageName;
}
