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

#include "models/patchdownloader.h"
#include "models/lotrodatmanager.h"

#include "widgets/chooseversiondialog.h"
#include "widgets/dialogwindow.h"

#include <QBitmap>
#include <QPainter>
#include <QPixmap>
#include <QDebug>
#include <QThread>
#include <QMouseEvent>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QtConcurrent/QtConcurrent>
#include <QGraphicsBlurEffect>
#include <QFont>
#include <QFontDatabase>
#include <QNetworkAccessManager>

#include <ui_statuswidget.h>
namespace Ui {
class StatusWidget;
}


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent, Qt::Window | Qt::FramelessWindowHint),
    ui(new Ui::MainWindow), menuHoverWidget(nullptr), menuHoverWidgetAnimation(nullptr)
{
    constructFonts();
    ui->setupUi(this);

    currently_active_entry = ui->menuentry_1;
    currently_hover_entry = nullptr;

    qDebug() << "Initialising Settings module";
    QSettings *settings = new QSettings(qApp->applicationDirPath() + "/legacy_v2.ini", QSettings::IniFormat);

    qDebug() << "Creating patch downloader instance & thread";
    lotro_functions_thread = new QThread();
    patch_updater = new PatchDownloader(settings);
    lotro_manager = new LotroDatManager(settings);

//    connect(patch_updater, &PatchDownloader::checkForUpdatesStarted, this, &MainWindow::onPatchDownloaderStarted, Qt::BlockingQueuedConnection);
//    connect(patch_updater, &PatchDownloader::checkForUpdatesFinished, this, &MainWindow::onPatchDownloaderFinished, Qt::BlockingQueuedConnection);
//    connect(lotro_manager, &LotroDatManager::processStarted, this, &MainWindow::onLotroManagerStarted, Qt::BlockingQueuedConnection);
//    connect(lotro_manager, &LotroDatManager::processFinished, this, &MainWindow::onLotroManagerFinished, Qt::BlockingQueuedConnection);
//    connect(lotro_manager, &LotroDatManager::caughtError, this, &MainWindow::onLotroManagerErrorOccured, Qt::BlockingQueuedConnection);

    connect(lotro_functions_thread, &QThread::finished, patch_updater, &QObject::deleteLater, Qt::QueuedConnection);
    connect(lotro_functions_thread, &QThread::finished, lotro_manager, &QObject::deleteLater, Qt::QueuedConnection);
    patch_updater->moveToThread(lotro_functions_thread);
    lotro_manager->moveToThread(lotro_functions_thread);
    lotro_functions_thread->start();

    qDebug() << "Initialising lotro manager...";
    QMetaObject::invokeMethod(lotro_manager, "InitialiseManager", Qt::QueuedConnection);

    status_widget = new StatusWidget(settings, patch_updater, lotro_manager, this);
    settings_widget = new SettingsWidget(settings, patch_updater, lotro_manager, this);
    help_widget = new HelpWidget(settings, patch_updater, lotro_manager, this);
    about_widget = new AboutWidget(settings, patch_updater, lotro_manager, this);

    choose_locale_dialog = new ChooseVersionDialog(settings, patch_updater, lotro_manager, this);
    choose_locale_dialog->resize(size());
    choose_locale_dialog->hide();
    connect(choose_locale_dialog, &ChooseVersionDialog::cancelled, this, &MainWindow::hideChooseVersionDialog);

    dialog_window = new DialogWindow(this);
    dialog_window->resize(size());

    ui->content_layout->addWidget(status_widget);
    ui->content_layout->addWidget(settings_widget);
    ui->content_layout->addWidget(help_widget);
    ui->content_layout->addWidget(about_widget);

    hideAllContentWidgets();
    status_widget->show();

    qDebug() << "Making background";

    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    current_bg_id = qrand() % MAX_PIXMAP_ID + 1;
    QPixmap background(":/backgrounds/bg" + QString::number(current_bg_id) + ".png");
    setupWindowBackgroundAndMask(background);

    setupMenuHoverWidget();

    qDebug() << "Initialising background updates";
    background_update_timer.setInterval(30 * 1000);
    connect(&background_update_timer, &QTimer::timeout, this, &MainWindow::randomChangeBackground);
    background_update_timer.start();

    qDebug() << "Initialising main window connections";
    makeConnections();

    qDebug() << "Installing event filters to clickable objects";
    setEventFilterRecursive(this);

    qDebug() << "Finishing main frame initialisation";
    show();
    QMetaObject::invokeMethod(patch_updater, "checkForUpdates");
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - dragPosition);
        event->accept();
    }
}

void MainWindow::resizeEvent(QResizeEvent * event)
{
    if (event->size().width() == -1 || event->size().height() == -1)
        return;

    int width = event->size().width();
    int height = event->size().height();

    window_width = width;
    window_height = height;

    // window_width * dpi / (default_window_width * default_dpi)
    updateFonts(window_width / default_window_width);

    ui->menu_widget->move(width * 320 / default_window_width, height * 34 / default_window_height);
    ui->menu_widget->resize(width * 650 / default_window_width, height * 53 / default_window_height);

    ui->content_area->move(0, height * 110 / default_window_height);
    ui->content_area->resize(width * 1000 / default_window_width, height * 538 / default_window_height);
    setupWindowBackgroundAndMask(current_bg);
    choose_locale_dialog->resize(event->size());

    ui->closeButton->setMinimumSize(width * 20 / default_window_width, height * 20 / default_window_height);
    ui->minimizeButton->setMinimumSize(width * 20 / default_window_width, height * 20 / default_window_height);

    choose_locale_dialog->move({0, 0});
    choose_locale_dialog->resize(event->size());

    dialog_window->move({0, 0});
    dialog_window->resize(size());
    updateFontSizes();
}

void MainWindow::randomChangeBackground()
{
    if (!qApp)
        return;

    qDebug() << "Starting background update";


    int next_pixmap_id = qrand() % MAX_PIXMAP_ID + 1;
    while (next_pixmap_id == current_bg_id) {
        next_pixmap_id = qrand() % MAX_PIXMAP_ID + 1;
    }
    qDebug() << "Next background id = " << next_pixmap_id;

    QPixmap *cur_bg = new QPixmap(current_bg);
    QPixmap *new_bg= new QPixmap(":/backgrounds/bg" + QString::number(next_pixmap_id) + ".png");
    current_bg_id = next_pixmap_id;

    QtConcurrent::run([cur_bg, new_bg, this](){
        const int iterations_num = 50;
        const int iteration_sleep = 40;
        const int starting_opacity_percent = 0;

        for (int i = 0; i < iterations_num - starting_opacity_percent && qApp; i++) {
            QPixmap composited_bg(*cur_bg);
            QPainter painter;
            painter.begin(&composited_bg);
            painter.setOpacity(double(starting_opacity_percent + i) / double(iterations_num));
            painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
            painter.drawPixmap(0,0, *new_bg);
            painter.end();
            QMetaObject::invokeMethod(this, "setupWindowBackgroundAndMask", Qt::QueuedConnection, Q_ARG(QPixmap, composited_bg));
            QThread::msleep(iteration_sleep);
        }
        delete cur_bg;
        delete new_bg;
        qDebug() << "Background update finished";
    });
}

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

void MainWindow::on_menuentry_1_clicked()
{
    currently_active_entry = ui->menuentry_1;
    hideAllContentWidgets();
    status_widget->show();
}

void MainWindow::on_menuentry_2_clicked()
{
    currently_active_entry = ui->menuentry_2;
    hideAllContentWidgets();
    settings_widget->show();
}

void MainWindow::on_menuentry_3_clicked()
{
    currently_active_entry = ui->menuentry_3;
    hideAllContentWidgets();
    help_widget->show();
}

void MainWindow::on_menuentry_4_clicked()
{
    currently_active_entry = ui->menuentry_4;
    hideAllContentWidgets();
    about_widget->show();
}

void MainWindow::onHoverMenuentry(MenuEntry *hovered_entry)
{
    if (currently_hover_entry != hovered_entry) {
        currently_hover_entry = hovered_entry;
        moveMenuHoverWidget(hovered_entry);
    }
}


void MainWindow::onPatchDownloaderStarted() {
    qDebug() << "Patch downloader started!";
}

void MainWindow::onPatchDownloaderFinished() {
    qDebug() << "Patch downloader finished!";

//    if (lotro_manager->Initialised()) {
//        QMetaObject::invokeMethod(lotro_manager, "InstallUpdates", Qt::QueuedConnection);
//    }
    return;
}

void MainWindow::onLotroManagerStarted(QString operation, QVector<QVariant> data) {
    qDebug() << "LotroManager: Started operation " << operation << " with parameters " << data;
    return;
}

void MainWindow::onLotroManagerFinished(QString operation, QVector<QVariant> data) {
    qDebug() << "LotroManager: Finished operation " << operation << " with parameters " << data;
//    if (operation == "")
    return;
}

void MainWindow::onLotroManagerErrorOccured(QString, QVector<QVariant>) {

}


void MainWindow::setupWindowBackgroundAndMask(QPixmap background)
{
    if (!qApp)
        return;
    current_bg = background;
    QPixmap scaled_bg = current_bg.scaled(width(), height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    current_mask = scaled_bg.mask();
    setMask(current_mask);

    QPalette palette;
    palette.setBrush(QPalette::Window, scaled_bg);
    setPalette(palette);
}

void MainWindow::makeConnections()
{
}

void MainWindow::setupMenuHoverWidget()
{
    menuHoverWidget = new QWidget(ui->menu_widget);
    menuHoverWidget->setStyleSheet("background-color: rgba(55, 37, 31, 230);");
    menuHoverWidget->resize(0, 0);

    connect(ui->menuentry_1, &MenuEntry::entryIsHovered, this, &MainWindow::onHoverMenuentry);
    connect(ui->menuentry_2, &MenuEntry::entryIsHovered, this, &MainWindow::onHoverMenuentry);
    connect(ui->menuentry_3, &MenuEntry::entryIsHovered, this, &MainWindow::onHoverMenuentry);
    connect(ui->menuentry_4, &MenuEntry::entryIsHovered, this, &MainWindow::onHoverMenuentry);

    currently_active_entry = ui->menuentry_1;
    menu_hover_checker_timer.setInterval(500);
    connect(&menu_hover_checker_timer, &QTimer::timeout, this, &MainWindow::checkMenuIsHovered);
    menu_hover_checker_timer.start();
}

void MainWindow::moveMenuHoverWidget(MenuEntry *target)
{
    if (menuHoverWidget->size() == QSize(0, 0)) {
        menuHoverWidget->resize(target->size() + QSize(10, 0));
        menuHoverWidget->move(target->pos() + QPoint(-5, 0));
    } else {
        if (menuHoverWidgetAnimation == nullptr)
            menuHoverWidgetAnimation = new QPropertyAnimation(menuHoverWidget, "geometry");
        else
            menuHoverWidgetAnimation->stop();

        menuHoverWidgetAnimation->setDuration(200);
        menuHoverWidgetAnimation->setStartValue(QRect(menuHoverWidget->pos(), menuHoverWidget->size()));
        menuHoverWidgetAnimation->setEndValue(QRect(target->pos() + QPoint(-5, 0), target->size() + QSize(10, 0)));
        menuHoverWidgetAnimation->start();
    }

    ui->menuentry_1->raise();
    ui->menuentry_2->raise();
    ui->menuentry_3->raise();
    ui->menuentry_4->raise();
}

void MainWindow::checkMenuIsHovered()
{
    QPoint pos = QCursor::pos();
    QWidget *hovered = qApp->widgetAt(pos);
    if (!hovered || hovered->objectName().size() < 4 ||
            (hovered->objectName().left(9) != "menuentry" && hovered->objectName() != "menu_widget")) {
        moveMenuHoverWidget(currently_active_entry);
        currently_hover_entry = nullptr;
    }
}

void MainWindow::hideAllContentWidgets()
{
    status_widget->hide();
    settings_widget->hide();
    help_widget->hide();
    about_widget->hide();
}

void MainWindow::showChooseVersionDialog()
{
//    QGraphicsBlurEffect *effect = new QGraphicsBlurEffect();
//    effect->setBlurRadius(10);
//    effect->setBlurHints(QGraphicsBlurEffect::QualityHint);
//    ui->content_area->setGraphicsEffect(effect);
    choose_locale_dialog->show();
}

void MainWindow::hideChooseVersionDialog()
{
//    ui->content_area->setGraphicsEffect(nullptr);
    choose_locale_dialog->hide();
}

void MainWindow::updateFontSizes()
{
    ui->menuentry_1->setFont(trajan_10pt);
    ui->menuentry_2->setFont(trajan_10pt);
    ui->menuentry_3->setFont(trajan_10pt);
    ui->menuentry_4->setFont(trajan_10pt);
}

void MainWindow::on_closeButton_clicked()
{
    hide();
    qApp->quit();
}

void MainWindow::on_minimizeButton_clicked()
{
    setWindowState(Qt::WindowMinimized);
}

void MainWindow::setEventFilterRecursive(QObject *widget)
{
    if (!widget)
        return;

    QStringList classes_to_set = {
        "QPushButton",
        "QCheckBox",
        "QComboBox"
    };

    if (classes_to_set.contains(widget->metaObject()->className())) {
        widget->installEventFilter(this);
    }

    foreach (QObject* child, widget->children()) {
        setEventFilterRecursive(child);
    }
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        mousePressEvent((QMouseEvent*)(event));
    }

    if (event->type() == QEvent::MouseMove) {
        mouseMoveEvent((QMouseEvent*)(event));
    }
    return false;
}
