#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QDir>
#include <QLocale>
#include <QLibraryInfo>
#include <QRandomGenerator>
#include "config_ulcc.h"
#include "ManagerDictionaries.h"
#include "FormSelectDictionary.h"
#include "FormSelectLanguage.h"
#include "FormAbout.h"
#include "FormHelp.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle(tr("Teaching children by pictures"));
    this->setWindowIcon(QIcon(QString(GLOBAL_PATH_USERDATA)+"/images/icons/ulcc.png"));

    currentIndexDictionaryImage=0;
    m_correct=0;
    m_total=0;
    m_wrong=0;
    waitAnswer=false;
    runGame=false;
    movie=nullptr;

    ui->label->setText(tr("Please select the dictionary"));
    ui->label_2->setText("");
    ui->label_3->setText("");
    ui->label_4->setText("");
    ui->label_5->setText("");

    ui->pushButton->setText(tr("Select dictionary"));
    ui->pushButton_2->setText(tr("Select language"));
    ui->pushButton_3->setText(tr("Info"));
    ui->pushButton_4->setText(tr("Help"));
    ui->pushButton_6->setVisible(false);

    initToolBar();

    // 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());

    selectDictionary = confSettings->value("Dictionary/Dictionary","").toString();
    selectLanguageDictionary = confSettings->value("Dictionary/LanguageDictionary","").toString();

    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(clickButton()));
    connect(ui->pushButton_2,SIGNAL(clicked(bool)),this,SLOT(clickButton()));
    connect(ui->pushButton_3,SIGNAL(clicked(bool)),this,SLOT(clickButton()));
    connect(ui->pushButton_4,SIGNAL(clicked(bool)),this,SLOT(clickButton()));
    connect(ui->pushButton_6,SIGNAL(clicked(bool)),this,SLOT(clickButtonNext()));

    refreshTranslate();
    startGame();
}

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

void MainWindow::modifyPosition(){
    // setting the position of the buttons
    ui->frame_3->move((ui->frame->width()-ui->frame_3->width())/2,0);

    if (runGame==false){
        ui->label->setGeometry(0,0,ui->frame_2->width(),ui->frame_2->height());
    }

    QSize rect(0,0);

    // setting the picture position
    QPixmap pix = QPixmap(ui->label->pixmap(Qt::ReturnByValue));
    if (!pix.isNull()){
        rect.setWidth(pix.width());
        rect.setHeight(pix.height());
    }

    if (ui->label->movie() && ui->label->movie()->isValid()){
        rect.setWidth(ui->label->movie()->frameRect().width());
        rect.setHeight(ui->label->movie()->frameRect().height());
    }


    if (rect.width()==0 or rect.height()==0) return;

    int maxWidth = ui->frame_2->width()-20;
    int maxHeight = ui->frame_2->height();

    ui->label->setFixedSize(rect.width(),rect.height());

    if (ui->label->height()>maxHeight){
        double deltaH = (double)ui->label->height()/(double)maxHeight;
        ui->label->setFixedWidth(ui->label->width()/deltaH);
        ui->label->setFixedHeight(maxHeight);
    }

    if (ui->label->width()>maxWidth){
        double deltaW = (double)ui->label->width()/(double)maxWidth;
        ui->label->setFixedWidth(maxWidth);
        ui->label->setFixedHeight(ui->label->height()/deltaW);
    }

    ui->label->move((ui->frame_2->width()-ui->label->width())/2,(ui->frame_2->height()-ui->label->height())/2);
}


void MainWindow::refreshImage(){   
    //ui->label->setMovie(nullptr);
    ui->label->setPixmap(QPixmap(currentDictionary.folder+"/"+currentDictionary.listImages.at(currentIndexDictionaryImage).image));

    QString ext = currentDictionary.listImages.at(currentIndexDictionaryImage).image.right(4);
    ext.replace(".","");

    if (movie->supportedFormats().indexOf(ext)!=-1){
        delete(movie);
        movie = new QMovie(currentDictionary.folder+"/"+currentDictionary.listImages.at(currentIndexDictionaryImage).image);
        ui->label->setMovie (movie);
        movie->setScaledSize(ui->label->size());
        movie->start ();
    }
    modifyPosition();


    QString locale="";

    if (selectLanguageDictionary=="system"){
        locale = QLocale::system().name();
    }else{
        locale=selectLanguageDictionary;
    }
    if (locale.indexOf("_")==-1) locale+="_"+locale.toUpper();


    if (!currentDictionary.listImages.at(currentIndexDictionaryImage).answer1.contains(locale)){
        locale="";
    }


    QString answer1 = currentDictionary.listImages.at(currentIndexDictionaryImage).answer1[locale];
    QString answer2 = currentDictionary.listImages.at(currentIndexDictionaryImage).answer2[locale];
    QString answer3 = currentDictionary.listImages.at(currentIndexDictionaryImage).answer3[locale];
    QString answer4 = currentDictionary.listImages.at(currentIndexDictionaryImage).answer4[locale];

    QStringList pos{answer1,answer2,answer3,answer4};
    QStringList pos2;
    indexCorrectAnswer=-1;
    while (pos.size()!=0){
        int index = QRandomGenerator::global()->bounded(pos.size());
        pos2.push_back(pos.at(index));
        if (indexCorrectAnswer==-1 and index==0) indexCorrectAnswer=pos2.size();
        pos.removeAt(index);
    }


    ui->pushButton->setText(pos2.at(0));
    ui->pushButton_2->setText(pos2.at(1));
    ui->pushButton_3->setText(pos2.at(2));
    ui->pushButton_4->setText(pos2.at(3));

    setColorPushButton(ui->pushButton,"black");
    setColorPushButton(ui->pushButton_2,"black");
    setColorPushButton(ui->pushButton_3,"black");
    setColorPushButton(ui->pushButton_4,"black");

    ui->pushButton_6->setVisible(true);
    ui->pushButton_6->setText(tr("Next"));
}

void MainWindow::refreshScore(){
    ui->label_2->setText(tr("Total:")+" "+QString::number(m_total));
    ui->label_3->setText(tr("Correct:")+" "+QString::number(m_correct));
    ui->label_4->setText(tr("Wrong:")+" "+QString::number(m_wrong));
}

void MainWindow::startGame(){
    QString path_dictionaries = QString(GLOBAL_PATH_USERDATA)+"/dictionaries/"+selectDictionary+"/dictionary.json";

    QFile file(path_dictionaries);
    if (!file.exists()){
        return;
    }

    DICTIONARY list = ManagerDictionaries::loadDictionary(path_dictionaries);
    currentDictionary.listImages.clear();

    while (list.listImages.size()!=0){
        int index = QRandomGenerator::global()->bounded(list.listImages.size());
        currentDictionary.listImages.push_back(list.listImages.at(index));
        list.listImages.removeAt(index);
    }
    currentDictionary.filename=list.filename;
    currentDictionary.folder=list.folder;
    currentDictionary.author=list.author;
    currentDictionary.description=list.description;

    currentIndexDictionaryImage=0;
    m_total=currentDictionary.listImages.size();
    m_correct=0;
    m_wrong=0;


    QString locale="";

    if (selectLanguageDictionary=="system"){
        locale = QLocale::system().name();
    }else{
        locale=selectLanguageDictionary;
    }
    if (locale.indexOf("_")==-1) locale+="_"+locale.toUpper();


    if (!currentDictionary.description.contains(locale)){
        if (currentDictionary.description.contains("en_EN")){
            locale="en_EN";
        }else{
            locale="";
        }
    }

    ui->label_5->setText(currentDictionary.description[locale]);

    refreshImage();
    refreshScore();

    waitAnswer=true;
    runGame=true;
}


void MainWindow::showEvent(QShowEvent *event){
    modifyPosition();
    QWidget::showEvent(event);
}

void MainWindow::clickButton(){
    QPushButton *button = reinterpret_cast<QPushButton*>(sender());
    int numberButton=-1;

    if (button==ui->pushButton) numberButton=1;
    if (button==ui->pushButton_2) numberButton=2;
    if (button==ui->pushButton_3) numberButton=3;
    if (button==ui->pushButton_4) numberButton=4;

    if (runGame==false){
        if (numberButton==1) clickButtonDictionary();
        //if (numberButton==2) ;
        if (numberButton==3) clickButtonInfo();
        if (numberButton==4) clickButtonHelp();
        return;
    }




    if (waitAnswer==false) return;

    if (numberButton==indexCorrectAnswer){
        m_correct++;
    }else{
        setColorPushButton(button,"red");
        m_wrong++;
    }

    if (indexCorrectAnswer==1) setColorPushButton(ui->pushButton,"green");
    if (indexCorrectAnswer==2) setColorPushButton(ui->pushButton_2,"green");
    if (indexCorrectAnswer==3) setColorPushButton(ui->pushButton_3,"green");
    if (indexCorrectAnswer==4) setColorPushButton(ui->pushButton_4,"green");

    refreshScore();
    waitAnswer=false;
}

void MainWindow::clickButtonNext(){
    if (runGame==false) return;

    setColorPushButton(ui->pushButton,"black");
    setColorPushButton(ui->pushButton_2,"black");
    setColorPushButton(ui->pushButton_3,"black");
    setColorPushButton(ui->pushButton_4,"black");

    if (currentIndexDictionaryImage<currentDictionary.listImages.size()-1){
        currentIndexDictionaryImage++;
        refreshImage();
        waitAnswer=true;
    }else{
        ui->label->setPixmap(QPixmap(QString(GLOBAL_PATH_USERDATA)+"/images/backgrounds/ribbon.png"));
        modifyPosition();
        ui->pushButton->setText(tr("Select dictionary"));
        ui->pushButton_2->setText(tr("Select language"));
        ui->pushButton_3->setText(tr("Info"));
        ui->pushButton_4->setText(tr("Help"));
        ui->pushButton_6->setVisible(false);
        runGame=false;
    }
}

void MainWindow::clickButtonDictionary(){
    FormSelectDictionary form(this);
    if (form.exec()){
        selectDictionary = form.getDictionary();
        selectLanguageDictionary = form.getLanguage();

        confSettings->setValue("Dictionary/Dictionary",selectDictionary);
        confSettings->setValue("Dictionary/LanguageDictionary",selectLanguageDictionary);

        startGame();
    }
}

void MainWindow::clickButtonLanguage(){
    FormSelectLanguage form(this);
    form.exec();
    refreshTranslate();
}

void MainWindow::clickButtonInfo(){
    FormAbout form(this);
    form.exec();
}

void MainWindow::clickButtonHelp(){
    FormHelp form(this);
    form.exec();
}

void MainWindow::resizeEvent(QResizeEvent *e){
    modifyPosition();
    QWidget::resizeEvent(e);
}


void MainWindow::initToolBar(){
    toolBar = new QToolBar("User");
    toolBar->setMovable(false);
    toolBar->setContextMenuPolicy(Qt::PreventContextMenu);
    addToolBar(Qt::TopToolBarArea, toolBar);

    toolBar->setIconSize(QSize(40, 40));

    accDictionary = new QAction(QIcon(QString(GLOBAL_PATH_USERDATA)+"/images/icons/dictionary.png"), tr("Dictionary"), this);
    accDictionary->setStatusTip(tr("Dictionary"));

    accLanguage = new QAction(QIcon(QString(GLOBAL_PATH_USERDATA)+"/images/icons/languages.png"), tr("Language"), this);
    accLanguage->setStatusTip(tr("Languages"));

    accHelp = new QAction(QIcon(QString(GLOBAL_PATH_USERDATA)+"/images/icons/help.png"), tr("Help"), this);
    accHelp->setStatusTip(tr("Help"));

    accInfo = new QAction(QIcon(QString(GLOBAL_PATH_USERDATA)+"/images/icons/info.png"), tr("About"), this);
    accInfo->setStatusTip(tr("About"));

    accExit = new QAction(QIcon(QString(GLOBAL_PATH_USERDATA)+"/images/icons/exit.png"), tr("Exit"), this);
    accExit->setStatusTip(tr("Exit"));

    toolBar->addAction(accDictionary);
    toolBar->addAction(accLanguage);
    toolBar->addAction(accHelp);
    toolBar->addAction(accInfo);
    toolBar->addAction(accExit);

    connect(accDictionary,SIGNAL(triggered()),this,SLOT(clickButtonDictionary()));
    connect(accLanguage,SIGNAL(triggered()),this,SLOT(clickButtonLanguage()));
    connect(accInfo,SIGNAL(triggered()),this,SLOT(clickButtonInfo()));
    connect(accHelp,SIGNAL(triggered()),this,SLOT(clickButtonHelp()));
    connect(accExit,SIGNAL(triggered()),this,SLOT(close()));

}


void MainWindow::setColorPushButton(QPushButton *button,QString color){
    if (color=="") color="black";

    button->setStyleSheet("\
        border-style: outset;\
        border-width: 2px;\
        border-color: "+color+";\
    ");

}

void MainWindow::refreshDynamicPushButtonText(){
    this->setWindowTitle(tr("Teaching children by pictures"));

    if (!ui->label->text().isEmpty()){
        ui->label->setText(tr("Please select the dictionary"));
    }

    if (runGame==false){
        ui->pushButton->setText(tr("Select dictionary"));
        ui->pushButton_2->setText(tr("Select language"));
        ui->pushButton_3->setText(tr("Info"));
        ui->pushButton_4->setText(tr("Help"));
        ui->pushButton_6->setText("");
    }else{
        ui->pushButton_6->setText(tr("Next"));
    }
}

void MainWindow::refreshTranslate(){
    QString locale = confSettings->value("ulcc/language",QLocale::system().bcp47Name()).toString();

    qApp->removeTranslator(&translator);
    qApp->removeTranslator(&qtTranslator);

    // save original
    if (listWidgetsRetranslateUi.size()==0){
        QList<QWidget*> l2 = this->findChildren<QWidget *>();
        for (auto &w:l2){
            QMap<QString,QString> m;
            m["toolTip"]=w->toolTip();
            m["whatsThis"]=w->whatsThis();
            m["windowTitle"]=w->windowTitle();
            m["statusTip"]=w->statusTip();
            listWidgetsRetranslateUi[w]=m;
        }

        QList<QAction*> l = this->findChildren<QAction *>();
        for (auto &w:l){
            QMap<QString,QString> m;
            m["text"]=w->text();
            m["toolTip"]=w->toolTip();
            m["whatsThis"]=w->whatsThis();
            m["statusTip"]=w->statusTip();
            listActionsRetranslateUi[w]=m;
        }

    }

    // set translator for app
    translator.load(QString(GLOBAL_PATH_USERDATA)+QString("/langs/ulcc_") + locale);
    qApp->installTranslator(&translator);

    // set translator for default widget's text (for example: QMessageBox's buttons)
#ifdef __WIN32
    qtTranslator.load("qt_"+locale,QString(GLOBAL_PATH_USERDATA)+"/translations");
#else
    qtTranslator.load("qt_"+locale,QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
    qApp->installTranslator(&qtTranslator);


    // retranslate UI
    QList<QWidget*> l2 = this->findChildren<QWidget *>();
    for (auto &w:l2){
        if (!w->toolTip().isEmpty()) w->setToolTip(tr(listWidgetsRetranslateUi[w]["toolTip"].toStdString().c_str()));
        if (!w->whatsThis().isEmpty()) w->setWhatsThis(tr(listWidgetsRetranslateUi[w]["whatsThis"].toStdString().c_str()));
        if (!w->windowTitle().isEmpty()) w->setWindowTitle(tr(listWidgetsRetranslateUi[w]["windowTitle"].toStdString().c_str()));
        if (!w->statusTip().isEmpty()) w->setStatusTip(tr(listWidgetsRetranslateUi[w]["statusTip"].toStdString().c_str()));
    }

    QList<QAction*> l = this->findChildren<QAction *>();
    for (auto &w:l){
        if (!w->text().isEmpty()) w->setText(tr(listActionsRetranslateUi[w]["text"].toStdString().c_str()));
        if (!w->toolTip().isEmpty()) w->setToolTip(tr(listActionsRetranslateUi[w]["toolTip"].toStdString().c_str()));
        if (!w->whatsThis().isEmpty()) w->setWhatsThis(tr(listActionsRetranslateUi[w]["whatsThis"].toStdString().c_str()));
        if (!w->statusTip().isEmpty()) w->setStatusTip(tr(listActionsRetranslateUi[w]["statusTip"].toStdString().c_str()));
    }

    refreshScore();
    refreshDynamicPushButtonText();
}
