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

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

#include "widgets/chooseversiondialog.h"

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent, Qt::Window | Qt::FramelessWindowHint),
    ui(new Ui::MainWindow), menuHoverWidget(nullptr), menuHoverWidgetAnimation(nullptr)
{
    setObjectName("ApplicationMainWindow");
    ui->setupUi(this);
    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, patch_updater);

    QObject::connect(lotro_functions_thread, &QThread::finished, patch_updater, &QObject::deleteLater, Qt::QueuedConnection);
    QObject::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);
    qDebug() << "Starting check for patch updates...";
    QMetaObject::invokeMethod(patch_updater, "checkForUpdates", Qt::QueuedConnection);
    qDebug() << "Starting installation for patch updates...";
    QMetaObject::invokeMethod(lotro_manager, "installUpdates", Qt::QueuedConnection);

    status_widget = new StatusWidget(settings, patch_updater, lotro_manager, this);    
    rusification_widget = new RusificationWidget(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);

    choose_locale_dialog = new ChooseVersionDialog(settings, patch_updater, lotro_manager, this);
//    choose_locale_dialog->move(this->rect().center() - choose_locale_dialog->rect().center());
    choose_locale_dialog->resize(size());
    choose_locale_dialog->hide();
    choose_locale_blur_effect = new QGraphicsBlurEffect(this);
    connect(choose_locale_dialog, &ChooseVersionDialog::cancelled, this, &MainWindow::hideChooseVersionDialog);

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

    ui->centralWidget->setStyleSheet("");

    hideAllContentWidgets();
    status_widget->show();

    qDebug() << "Making fonts and making background";
    changeFontSizeRecursive(100, this);

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

    updateGeometry();
    repaint();

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

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

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

    qDebug() << "Finishing main frame initialisation";
    show();
}

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);
//        choose_locale_dialog->move(this->rect().center() - choose_locale_dialog->rect().center());
        event->accept();
    }
}

void MainWindow::resizeEvent(QResizeEvent * event)
{
    int width = event->size().width();
    int height = event->size().height();

    ui->menu_widget->move(width * 300 / 900, height * 35 / 650);
    ui->menu_widget->resize(width * 570 / 900, height * 50 / 650);

    ui->content_area->move(0, height * 110 / 650);
    ui->content_area->resize(width * 900 / 900, height * 515 / 650);
    setupWindowBackgroundAndMask(current_bg);
//    choose_locale_dialog->move(this->rect().center() - choose_locale_dialog->rect().center());
    choose_locale_dialog->resize(size());
}

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 = 150;
        const int iteration_sleep = 75;

        for (int i = 0; i < iterations_num && qApp; i++) {
            QPainter painter;
            painter.begin(cur_bg);
            painter.setOpacity(double(10 + 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, *cur_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()
{
    hideAllContentWidgets();
    status_widget->show();
}

void MainWindow::on_menuentry_2_clicked()
{
    hideAllContentWidgets();
    settings_widget->show();
}

void MainWindow::on_menuentry_3_clicked()
{
    hideAllContentWidgets();
    rusification_widget->show();
}

void MainWindow::on_menuentry_4_clicked()
{
    hideAllContentWidgets();
    help_widget->show();
}

void MainWindow::onHoverMenuentry()
{
    moveMenuHoverWidget(MenuEntry::getHoverLabel());
}

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, 250);");
    menuHoverWidget->resize(0, 0);

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

    MenuEntry::setActiveLabel(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(MenuEntry::getActiveLabel());
        MenuEntry::setHoverLabel(nullptr);
    }
}

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

void MainWindow::changeFontSizeRecursive(size_t percent, QWidget *widget)
{
    if (!widget)
        return;
    QFont widget_font = widget->font();
    QString widget_name = widget->objectName();

    if (widget_name.contains("menuentry"))
        widget_font.setPixelSize(small_font_size * percent / 100);
    if (widget_name.contains("_small"))
        widget_font.setPixelSize(small_font_size * percent / 100);
    if (widget_name.contains("_common"))
        widget_font.setPixelSize(common_font_size * percent / 100);
    if (widget_name.contains("_title"))
        widget_font.setPixelSize(title_font_size * percent / 100);
    if (widget_name.contains("_supertitle"))
        widget_font.setPixelSize(supertitle_font_size * percent / 100);
    if (widget_name.contains("_bigbutton"))
        widget_font.setPixelSize(bigbutton_font_size * percent / 100);

    widget->setFont(widget_font);

    for (QObject* child : widget->children())
        if (child->isWidgetType()) {
            QWidget* w = qobject_cast<QWidget *>(child);
            changeFontSizeRecursive(percent, w);
            w->resize(w->sizeHint());
        }
}

void MainWindow::showChooseVersionDialog()
{
    choose_locale_blur_effect->setBlurRadius(10);
    choose_locale_blur_effect->setBlurHints(QGraphicsBlurEffect::QualityHint);
    ui->content_area->setGraphicsEffect(choose_locale_blur_effect);
    choose_locale_dialog->show();
}

void MainWindow::hideChooseVersionDialog()
{
    choose_locale_blur_effect->setBlurRadius(0);
    choose_locale_blur_effect->setBlurHints(QGraphicsBlurEffect::QualityHint);
    ui->content_area->setGraphicsEffect(choose_locale_blur_effect);
    choose_locale_dialog->hide();
}

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