#include "ManagerDictionaries.h"

#include <QFile>
#include <QDir>
#include <QRegExp>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMessageBox>
#include <QRandomGenerator>
#include <QDebug>

#include <functional>

DICTIONARY ManagerDictionaries::loadDictionary(QString fileName){
    DICTIONARY result;

    QByteArray val;
    QFile file;
    file.setFileName(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        QMessageBox::critical(0,"ulcc",QObject::tr("Error while opening")+" "+fileName+"\n"+file.errorString());
        return result;
    }
    val = "{"+file.readAll()+"}";
    file.close();

    QJsonDocument document = QJsonDocument::fromJson(val);
    if (document.isEmpty()){
        QMessageBox::critical(0,"ulcc",fileName+" "+QObject::tr("is not valid"));
        return result;
    }
    QJsonObject root = document.object();

    result.filename=fileName;
    QStringList folders = fileName.split(QRegularExpression("[/\\\\]"));
    result.folder =fileName.mid(0,fileName.size()-folders.at(folders.size()-1).size()-1);

    result.author = root.value("author").toString();
    result.description[""] = root.value("description").toString();

    QJsonArray arrImages = root.value("images").toArray();
    for (int i=0;i<arrImages.size();i++){
        DICTIONARY_IMAGES image;

        image.image = arrImages.at(i).toObject().value("image").toString();
        image.answer1[""] = arrImages.at(i).toObject().value("answer1").toString().toUpper();
        image.answer2[""] = arrImages.at(i).toObject().value("answer2").toString().toUpper();
        image.answer3[""] = arrImages.at(i).toObject().value("answer3").toString().toUpper();
        image.answer4[""] = arrImages.at(i).toObject().value("answer4").toString().toUpper();

        if (image.answer1[""]==""){
            image.answer1[""] = arrImages.at(i).toObject().value("answer").toString().toUpper();
        }

        result.listImages.push_back(image);
    }

    std::function<QString(int)> findWord = [&result](int ind) {
        QString string1 = result.listImages[ind].answer1[""];
        QString string2 = result.listImages[ind].answer2[""];
        QString string3 = result.listImages[ind].answer3[""];
        QString string4 = result.listImages[ind].answer4[""];

        while(true){
            int index = QRandomGenerator::global()->bounded(result.listImages.size());
            QString findString = result.listImages.at(index).answer1[""];
            if (findString!=string1){
                if (result.listImages.size()>4){
                    if (findString!=string2 and findString!=string3 and findString!=string4){
                        return findString;
                    }
                }else{
                    return findString;
                }
            }
        }
    };

    // add answers where there are none
    for (int i = 0; i < result.listImages.size(); ++i) {
        if (result.listImages.at(i).answer2[""]=="") result.listImages[i].answer2[""]=findWord(i);
        if (result.listImages.at(i).answer3[""]=="") result.listImages[i].answer3[""]=findWord(i);
        if (result.listImages.at(i).answer4[""]=="") result.listImages[i].answer4[""]=findWord(i);
    }


    // answer translations
    QDir dir(result.folder+"/languages");
    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot);
    QRegExp rx("^(.*)(.lng)$");
    QFileInfoList list = dir.entryInfoList();
    for (QFileInfo fileInfo : list) {
        if (rx.indexIn(fileInfo.fileName())!=-1){
            QString lang_code = rx.cap(1);
            if (lang_code.indexOf("_")==-1) lang_code+="_"+lang_code.toUpper();

            QFile file(result.folder+"/languages/"+fileInfo.fileName());
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
                while (!file.atEnd()) {
                    QString line = file.readLine();
                    line.replace(QRegularExpression("(\\s+)$"),"");
                    QStringList pairs = line.split("=");
                    if (pairs.size()!=2) continue;

                    for (int i=0;i<result.listImages.size();i++){
                        if(result.listImages[i].answer1[""].toUpper()==pairs.at(0).toUpper()) result.listImages[i].answer1[lang_code] = pairs.at(1).toUpper();
                        if(result.listImages[i].answer2[""].toUpper()==pairs.at(0).toUpper()) result.listImages[i].answer2[lang_code] = pairs.at(1).toUpper();
                        if(result.listImages[i].answer3[""].toUpper()==pairs.at(0).toUpper()) result.listImages[i].answer3[lang_code] = pairs.at(1).toUpper();
                        if(result.listImages[i].answer4[""].toUpper()==pairs.at(0).toUpper()) result.listImages[i].answer4[lang_code] = pairs.at(1).toUpper();
                        if(result.description[""].toUpper()==pairs.at(0).toUpper()) result.description[lang_code] = pairs.at(1);
                    }
                }
                file.close();
            }
        }
    }



    return result;
}
