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

#include "widgets/chooseversiondialog.h"
#include "widgets/dialogwindow.h"
#include "models/patchlist.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(PatchList *legacy_patches, QWidget *parent)
    : QMainWindow(parent, Qt::Window | Qt::FramelessWindowHint)
    , legacy_patches_(legacy_patches)
    , ui(new Ui::MainWindow)
    , current_active_entry_(nullptr)
    , current_hovered_entry_(nullptr)
    , status_widget_(nullptr)
    , settings_widget_(nullptr)
    , help_widget_(nullptr)
    , about_widget_(nullptr)
    , choose_locale_dialog_(nullptr)
    , dialog_window_(nullptr)
    , menu_hover_widget_(nullptr)
    , menu_hover_widget_animation_(nullptr)
{
    constructFonts();
    ui->setupUi(this);

    current_active_entry_ = ui->menuentry_1;
    current_hovered_entry_ = nullptr;

    qDebug() << __FUNCTION__ << "Initialising main frame...";
    status_widget_ = new StatusWidget(legacy_patches_, this);
    settings_widget_ = new SettingsWidget(legacy_patches_, this);
    help_widget_ = new HelpWidget(legacy_patches_, this);
    about_widget_ = new AboutWidget(legacy_patches_, this);

    ui->content_layout->addWidget(status_widget_);
    ui->content_layout->addWidget(settings_widget_);
    ui->content_layout->addWidget(help_widget_);
    ui->content_layout->addWidget(about_widget_);

    // Adding patch update triggers on settings state changes
    connect(settings_widget_, &SettingsWidget::SettingsChanged, legacy_patches_, &PatchList::stopAutoUpdate);
    connect(settings_widget_, &SettingsWidget::SettingsReset, legacy_patches_, &PatchList::startAutoUpdate);
    connect(settings_widget_, &SettingsWidget::SettingsApplied, legacy_patches_, &PatchList::initialize);


    hideAllContentWidgets();
    status_widget_->show();

    qDebug() << __FUNCTION__ << "Initialising additional frames...";

    choose_locale_dialog_ = new ChooseVersionDialog(legacy_patches_->getManager(), this);
    choose_locale_dialog_->resize(size());
    choose_locale_dialog_->hide();
    connect(choose_locale_dialog_, &ChooseVersionDialog::cancelled, choose_locale_dialog_, &ChooseVersionDialog::hide);

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

    qDebug() << __FUNCTION__ << "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() << __FUNCTION__ << "Initialising background updates";
    background_update_timer_.setInterval(30 * 1000);
    connect(&background_update_timer_, &QTimer::timeout, this, &MainWindow::randomChangeBackground);
    background_update_timer_.start();

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

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

    qDebug() << __FUNCTION__ << "Resizing window due to Settings value";
    int window_scale_factor = Settings::getValue("General/UI_scale").toInt();;
    window_width = default_window_width * window_scale_factor / 100;
    window_height = default_window_height * window_scale_factor / 100;
    resize(window_width, window_height);

    qDebug() << __FUNCTION__ << "Finished main frame initialisation";
    show();
}

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

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - drag_position_);
        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 * 530 / 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() << __FUNCTION__ << "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() << __FUNCTION__ << "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() << __FUNCTION__ << "Background update finished";
    });
}

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

void MainWindow::showMessageDialog(QObject* emitter, QString message, QString ok_button_text, QString cancel_button_text)
{
    QMessageBox msg_box;
    msg_box.setText(message);
    msg_box.setStandardButtons(QMessageBox::NoButton);

    QPushButton* ok_button = nullptr;
    QPushButton* cancel_button = nullptr;

    if (!ok_button_text.isEmpty()) {
        ok_button = new QPushButton(&msg_box);
        ok_button->setText(ok_button_text);
        msg_box.addButton(ok_button, QMessageBox::AcceptRole);
    }

    if (!cancel_button_text.isEmpty()) {
        cancel_button = new QPushButton(&msg_box);
        cancel_button->setText(cancel_button_text);
        msg_box.addButton(cancel_button, QMessageBox::RejectRole);
    }

    int result = msg_box.exec();
    emit messageDialogFinished(emitter, result);
}

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

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

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

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

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

void MainWindow::setupWindowBackgroundAndMask(QPixmap background)
{
    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::onPatchOperationsStarted()
{
    show_warning_on_close = true;
}

void MainWindow::onPatchOperationsFinished()
{
    show_warning_on_close = false;
}

void MainWindow::makeConnections()
{
    connect(legacy_patches_, &PatchList::patchOperationsStarted, this, &MainWindow::onPatchOperationsStarted);
    connect(legacy_patches_, &PatchList::patchOperationsFinished, this, &MainWindow::onPatchOperationsFinished);
}

void MainWindow::setupMenuHoverWidget()
{
    menu_hover_widget_ = new QWidget(ui->menu_widget);
    menu_hover_widget_->setStyleSheet("background-color: rgba(55, 37, 31, 230);");
    menu_hover_widget_->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);

    current_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 (menu_hover_widget_->size() == QSize(0, 0)) {
        menu_hover_widget_->resize(target->size() + QSize(10, 0));
        menu_hover_widget_->move(target->pos() + QPoint(-5, 0));
    } else {
        if (menu_hover_widget_animation_ == nullptr)
            menu_hover_widget_animation_ = new QPropertyAnimation(menu_hover_widget_, "geometry");
        else
            menu_hover_widget_animation_->stop();

        menu_hover_widget_animation_->setDuration(200);
        menu_hover_widget_animation_->setStartValue(QRect(menu_hover_widget_->pos(), menu_hover_widget_->size()));
        menu_hover_widget_animation_->setEndValue(QRect(target->pos() + QPoint(-5, 0), target->size() + QSize(10, 0)));
        menu_hover_widget_animation_->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(current_active_entry_);
        current_hovered_entry_ = nullptr;
    }
}

void MainWindow::hideAllContentWidgets()
{
    status_widget_->hide();
    settings_widget_->hide();
    help_widget_->hide();
    about_widget_->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()
{
    close();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (show_warning_on_close) {
        auto result = QMessageBox::question(this, "Подтвердите действие", "Внимание! В настоящий момент выполняются процессы установки/обновления.\n"
                                                            "Выход из приложения может привести к ошибкам и повреждению файлов игры.\n\n"
                                                            "Вы уверены, что хотите прервать работу Наследия?");
        if (result == QMessageBox::Yes) {
            qApp->quit();
        }
    } else {
        qApp->quit();
    }
    event->ignore();
}

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::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;
}
