#include "app.h"
#include "filesystem.h"

Helper::Helper()
{

}

int Helper::getVersion(QString string) {
    std::string str(string.toLatin1().data());
    int version = 0;
    for (unsigned i = str.find("_v") + 2; i < str.find("_v") + 7; i += 2) {
        version = version * 10 + (str[i] - '0');
    }
    return version;
}

void Helper::checkTab(QString tabname){
    App *app = &App::getInstance();
    QList<QGroupBox *> boxes = app->window->findChildren<QGroupBox *> ();
    foreach (QGroupBox * box, boxes){
        if(box->parent()->objectName() == "centralWidget"){
            QLabel* boximage = app->window->findChild<QLabel*>(box->objectName() + "Image");
            if(box->objectName() == tabname){
                box->show();
                if(boximage != nullptr) boximage->show();
            } else {
                box->hide();
                if(boximage != nullptr) boximage->hide();
            }
        }
    }
    app->window->ui->serversbox->show();
}

void Helper::loadNews(){
    App *app = &App::getInstance();
    app->logSectionStart("Загружаем скин лаунчера");
    qInfo("%s:%i: %s", __FILE__, __LINE__, "Загрузка новостей с сайта");
    QString response = app->network->query(app->config->getValue("Network", "news"));
    if(response == "error"){
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Отсутствует связь с сервером. Прервано.");
        app->logSectionEnd();
        return;
    }
    QStringList data = response.split(":::");
    qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Получено новостей - ", QString::number(data.count()).toLocal8Bit().data());
    int counter = 1;
    foreach(QString news, data){
        qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Начинаем размещение новости №", QString::number(counter).toLocal8Bit().data());
        QStringList item = news.split("|");
        QLabel* image = app->window->ui->newsbox->findChild<QLabel*>("news" + QString::number(counter) + "Image");
        QLabel* title = app->window->ui->newsbox->findChild<QLabel*>("news" + QString::number(counter) + "Title");
        QLabel* teaser = app->window->ui->newsbox->findChild<QLabel*>("news" + QString::number(counter) + "Teaser");
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Устанавливаем миниатюру новости");
        QByteArray bytes = app->network->query_binary(item[0]);
        QImage img(36, 36, QImage::Format_Indexed8);
        img.loadFromData(bytes);
        QString skin = app->helper->getSkinName();
        if(img.bits() == nullptr){
            qInfo("%s:%i: %s", __FILE__, __LINE__, "Миниатюра не найдена, устанавливаем заглушку");
            img.load(":/res/styles/" + skin + "/nophoto.jpg");
        }
        image->setPixmap(QPixmap::fromImage(img));
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Применяем HTML-цвета");
        QString hrefcolor = app->helper->htmlColors.contains("a") ? app->helper->htmlColors.lowerBound("a").value() : "blue";
        QString html = "<a href=\"" + item[3] +"\" style=\"color:" + hrefcolor + "; text-decoration:none;\">" + item[1] + "</a>";
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Размещаем тексты");
        title->setText(html);
        teaser->setText(item[2]);
        counter = counter+1;
    }
    qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
    app->logSectionEnd();
}

void Helper::loadHelp(){
    App *app = &App::getInstance();
    app->logSectionStart("Создание справки");
    QFile file(QApplication::applicationDirPath() + "/readme.html");

    if(file.open(QFile::ReadOnly | QFile::Text)){
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Справка загружена. Устанавливаем HTML-цвета и выводим.");
        app->window->ui->textBrowser->setHtml("");
        QString content = file.readAll();

        app->stylehtml = "<style>";
        for(auto e : app->helper->htmlColors.keys()){
            app->stylehtml = app->stylehtml + e + "{color:" + app->helper->htmlColors.value(e) + ";}";
        }


        QFile styleF;
        QString skin = app->helper->getSkinName();
        styleF.setFileName(app->app_folder + "styles/" + skin + "/readme.css");
        if(styleF.open(QFile::ReadOnly)){
           app->stylehtml = "<html><head><style type=\"text/css\">" + app->stylehtml + styleF.readAll();
        }

        app->stylehtml = app->stylehtml + "</style></head>";

        app->window->ui->textBrowser->setHtml(app->stylehtml + content);
        app->window->ui->textBrowser->document()->setDefaultStyleSheet(styleF.readAll());
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
        app->logSectionEnd();
    } else {
        qWarning("%s:%i: %s", __FILE__, __LINE__, "Не удалось получить информацию с сервера");
        qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
        app->logSectionEnd();
    }
}

void Helper::hideAll(){
    qInfo("%s:%i: %s", __FILE__, __LINE__, "Прячем ненужные элементы.");
    App *app = &App::getInstance();
    app->window->ui->optbox->hide();
    app->window->ui->optboxImage->hide();
    app->window->ui->newsbox->hide();
    app->window->ui->newsboxImage->hide();
    app->window->ui->helpbox->hide();
    app->window->ui->helpboxImage->hide();
    app->window->ui->aboutbox->hide();
    app->window->ui->aboutboxImage->hide();
    app->window->ui->dialogbox->hide();
    app->window->ui->loader->hide();
    app->window->ui->dialogList->hide();
    app->window->ui->startbox->hide();    
    qInfo("%s:%i: %s", __FILE__, __LINE__, "Устанавливаем всплывающие подсказки.");
    app->window->ui->goOriginal->setToolTip("Запуск оригинальной версии игры");
    app->window->ui->goLocal->setToolTip("Запуск русской версии игры");
    app->window->ui->goCancel->setToolTip("Вернуться обратно");
    app->window->ui->goProgress->hide();
    app->window->ui->goHint->hide();
    app->window->ui->footRed->hide();
    app->window->ui->footYellow->hide();
}

void Helper::setAbout(){
    App *app = &App::getInstance();
    app->logSectionStart("О нас");
    qInfo("%s:%i: %s", __FILE__, __LINE__, "Размещаем информацию о хороших людях.");

    app->window->ui->programmerslist->setText("Gi1dor, coder");
    app->window->ui->designerslist->setText("Чирик, valyot, Quilanar, Eodoro");

    app->window->ui->translatorslist->setText("<b>Переводчики:</b> Pioneer, kitkatik134, Anadomiel, Progylkin, Drazgar, Rhymer, Влад Блюденов, "
                                              "Buddy, Quilanar, Ferdik, Alcassar, Чирик, Tukbard<br><br>"
                                              "<b>Модераторы:</b> Eodoro, unnamedartist, Marty, valyot, Invizet");

    app->window->ui->helperslist->setText("Menelhad, Мурзилка, Pastor, Alvees, Mirta, иван петров, vensys, "
                                          "Arkelas, Чеширская Улыбка, Shanishka70");
}

void Helper::findSkins(){
    App *app = &App::getInstance();
    app->logSectionStart("Темы оформления");
    qInfo("%s:%i: %s", __FILE__, __LINE__, "Производим поиск доступных тем.");
    QDir dir(QApplication::applicationDirPath() + "/styles");
    QStringList skins = dir.entryList(QDir::Dirs | QDir::AllDirs | QDir::NoDotAndDotDot);
    app->window->ui->skinSelect->addItems(skins);
    QString skinname = app->config->getValue("Global", "current_theme");
    app->window->ui->skinSelect->setCurrentText(skinname);

    qInfo("%s:%i: %s", __FILE__, __LINE__, "Устанавливаем отметку о файле локализации.");
    QString file = app->config->getValue("Local", "file");
    if(file == "client_local_English.dat") app->window->ui->enButton->setEnabled(false);
    if(file == "client_local_DE.dat") app->window->ui->deButton->setEnabled(false);
    if(file == "client_local_FR.dat") app->window->ui->frButton->setEnabled(false);
    qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
    app->logSectionEnd();
}

QString Helper::getSkinName() {
    App *app = &App::getInstance();
    QString skin = app->config->getValue("Global", "current_theme");
    if(skin == "-1") skin = app->config->getValue("Global", "default_theme");
    qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Текущая тема оформления: ", skin.toLocal8Bit().data());
    return skin;
}

void Helper::applyShadow(QWidget * obj, QString color, int blur, int offset_x, int offset_y){
    QGraphicsDropShadowEffect *pLabelTextShadowEffect = new QGraphicsDropShadowEffect(obj);
    pLabelTextShadowEffect->setColor(QColor(color));
    pLabelTextShadowEffect->setBlurRadius(blur);
    pLabelTextShadowEffect->setOffset(offset_x, offset_y);
    obj->setGraphicsEffect(pLabelTextShadowEffect );

}

void Helper::myDialogBox(QString text, QString info, QString okText, QString cancelText, QString image, QString okAnswer, QString cancelAnswer,
                        int w, int h, bool, bool is_cancel, bool prevent_dublicates){
    if (last_message_msg == info && prevent_dublicates)
        return;

    last_message_msg = info;

    App *app = &App::getInstance();

    if(okAnswer == "") okAnswer = "close";
    app->helper->dialog_ok_answer = okAnswer;
    if(cancelAnswer == "") cancelAnswer = "close";
    app->helper->dialog_cancel_answer = cancelAnswer;

    app->window->ui->okButton->setText(okText);
    app->window->ui->cancelButton->setText(cancelText);
    app->window->ui->dialogbox->setGeometry(0, 0, app->window->width(), app->window->height());

    QSettings settings( app->config->getSkinFile(), QSettings::IniFormat );
    settings.beginGroup("mainWindow");
    int left = (settings.value("width").toInt() - w)/2;
    int top = (settings.value("height").toInt() - h)/2;
    app->window->ui->dialog->setGeometry(QRect(left, top, w, h));
    settings.endGroup();

    int image_height = app->window->ui->dialog->rect().height() - app->window->ui->dialogHeader->rect().height();
    app->window->ui->dialogImage->setGeometry(0,
        app->window->ui->dialogHeader->rect().bottom(),
        image_height/2 ,image_height
     );

    QString skin = app->helper->getSkinName();
    QString iconpath = "";
    iconpath = FileSystem::fileExists("styles/" + skin + "/" + image) ? "styles/" + skin + "/" + image : ":/res/styles/" + skin + "/" + image;
    QPixmap icon(iconpath);

    app->window->ui->dialogImage->setPixmap(icon.scaled(app->window->ui->dialogImage->width(), app->window->ui->dialogImage->height()));
    if(icon.isNull()){
        app->window->ui->dialogImage->setGeometry(QRect(10, 10, 10, 10));
    }

    app->window->ui->dialogHeader->setGeometry(
                app->window->ui->dialogHeader->rect().left(),
                app->window->ui->dialogHeader->rect().top(),
                app->window->ui->dialog->rect().width(),
                app->window->ui->dialogHeader->rect().height()
    );

    app->window->ui->dialogInfo->setGeometry(app->window->ui->dialogImage->rect().right(),
        app->window->ui->dialogHeader->rect().bottom(),
         app->window->ui->dialog->rect().width() - app->window->ui->dialogImage->rect().width()-7,
         image_height - app->window->ui->cancelButton->height()
     );



    if(is_cancel){
       app->window->ui->cancelButton->setGeometry(
           app->window->ui->dialog->rect().left() + app->window->ui->dialog->width() - app->window->ui->cancelButton->width() - 20,
           app->window->ui->dialog->rect().bottom() - app->window->ui->cancelButton->height() - 10,
           app->window->ui->cancelButton->width(),
           app->window->ui->cancelButton->height()
        );
       app->window->ui->okButton->setGeometry(
           app->window->ui->dialog->rect().left() + app->window->ui->dialog->width() - app->window->ui->cancelButton->width() - app->window->ui->cancelButton->width() - 40,
           app->window->ui->dialog->rect().bottom() - app->window->ui->cancelButton->height() - 10,
           app->window->ui->cancelButton->width(),
           app->window->ui->cancelButton->height()
        );
    } else {
        app->window->ui->cancelButton->setGeometry(-1000,-1000, app->window->ui->cancelButton->width(), app->window->ui->cancelButton->height());
        app->window->ui->okButton->setGeometry(
            app->window->ui->dialog->rect().left() + app->window->ui->dialog->width() - app->window->ui->cancelButton->width() - 20,
            app->window->ui->dialog->rect().bottom() - app->window->ui->cancelButton->height() - 10,
            app->window->ui->cancelButton->width(),
            app->window->ui->cancelButton->height()
         );
    }

    app->window->ui->dialogHeader->setText(text);
    app->window->ui->dialogInfo->setText(info);
    app->window->ui->dialogImage->setText("");
    app->window->ui->dialogbox->show();
}

void Helper::setState(QString state){
    App *app = &App::getInstance();
    if(state == "busy"){
        app->window->ui->closeButton->setEnabled(false);
        app->window->ui->enterButton->setEnabled(false);
        app->window->ui->lotropathButton->setEnabled(false);
        app->window->ui->repairButton->setEnabled(false);
        app->state = "busy";
        app->window->ui->loader->show();
    }

    if(state == "free"){
        app->window->ui->closeButton->setEnabled(true);
        app->window->ui->enterButton->setEnabled(true);
        app->window->ui->lotropathButton->setEnabled(true);
        app->window->ui->repairButton->setEnabled(true);
        app->state = "free";
        app->window->ui->loader->hide();
    }

    if(state == "nofolder"){
        app->window->ui->enterButton->setEnabled(false);
        app->state = "nofolder";
        app->window->ui->loader->hide();
    }

    if(state == "runfirst"){
        app->window->ui->enterButton->setEnabled(false);
        app->window->ui->repairButton->setEnabled(false);
        app->state = "runfirst";
        app->window->ui->loader->hide();
        QString info = "Вы запускаете программу русификации LotRO впервые. Мастер установки поможет вам настроить программу для ее дальнейшего использования. Сейчас будет осуществлена попытка автоматически определить каталог с игрой. Для продолжения нажмите «Далее».";
        app->helper->myDialogBox("Добро пожаловать!", info, "Далее", "Отмена", "gandalf.png", "close gamefind", "", 400, 200, true, false);
    }
}

int Helper::dateToTimestamp(QString customDateString, QString format){
    int timestamp = QDateTime::fromString(customDateString, format).toTime_t();
    return timestamp;
}

void Helper::addComboItem(QComboBox* combo, QString itemName, QIcon* icon){
    combo->insertItem(0, itemName);
    combo->setItemIcon(0, *icon);
}

void Helper::replaceSkin(QString name){
    App *app = &App::getInstance();
    QString text = "Смена темы оформления";
    QString info = "Выбрана тема " + name + ". Изменения вступят в силу при следующем запуске лаунчера.";
    //app->helper->myDialogBox(text, info, "OK", "Отмена", "gandalf.png", "", "", 400, 120, true, false);

    qInfo("%s:%i: %s", __FILE__, __LINE__, "Оформляем главное окно.");

    QFile styleF;
    QString skin = app->helper->getSkinName();
    styleF.setFileName(app->app_folder + "styles/" + name + "/style.css");
    styleF.open(QFile::ReadOnly);
    QString qssStr = styleF.readAll();

    qApp->setStyleSheet(qssStr);

    QPixmap maskPix(":/res/styles/" + name + "/bg.png");
    QPixmap maskPixLocal(app->app_folder + "styles/" + name + "/bg.png");
    maskPix = maskPix.isNull() ? maskPixLocal : maskPix;
    app->window->setMask(maskPix.mask());

    QString color = app->helper->htmlColors.contains("a") ? app->helper->htmlColors.lowerBound("a").value() : "blue";
    app->config->loadSkin();
    QString hrefcolor = app->helper->htmlColors.contains("a") ? app->helper->htmlColors.lowerBound("a").value() : "blue";

    QString newtext = app->window->ui->news1Title->text().replace(color, hrefcolor);
    app->window->ui->news1Title->setText(newtext);

    newtext = app->window->ui->news2Title->text().replace(color, hrefcolor);
    app->window->ui->news2Title->setText(newtext);

    newtext = app->window->ui->news3Title->text().replace(color, hrefcolor);
    app->window->ui->news3Title->setText(newtext);

    newtext = app->window->ui->news4Title->text().replace(color, hrefcolor);
    app->window->ui->news4Title->setText(newtext);

    app->helper->loadHelp();

    QMovie * movie = new QMovie(":/res/styles/" + skin + "/loader.gif");
    if(!movie->isValid()) movie = new QMovie(app->app_folder + "styles/" + skin + "/loader.gif");
    app->window->ui->loader->setMovie(movie);
    movie->setScaledSize(QSize(app->window->ui->loader->width(), app->window->ui->loader->height()));
    movie->start();
}
