#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "models/lotrodatmanager.h"

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

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

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


    qDebug() << "Creating lotro manager instance & thread";
    lotro_mgr_thread = new QThread();
    lotro_manager = new LotroDatManager(settings);
    QObject::connect(lotro_mgr_thread, &QThread::finished, lotro_manager, &QObject::deleteLater, Qt::QueuedConnection);
    lotro_manager->moveToThread(lotro_mgr_thread);
    lotro_mgr_thread->start();

    qDebug() << "Creating widgets";
    qDebug() << "1";
    browse_widget = new BrowseWidget(lotro_manager, settings, this);
    qDebug() << "2";
    import_widget = new ImportWidget(lotro_manager, settings, this);
    qDebug() << "3";
    export_widget = new ExportWidget(lotro_manager, settings, this);
    qDebug() << "4";
    manage_widget = new ManageWidget(lotro_manager, settings, this);
    connect(manage_widget, &ManageWidget::disableMenuItems, this, &MainWindow::disableMenuItems);
    connect(manage_widget, &ManageWidget::enableMenuItems, this, &MainWindow::enableMenuItems);

    qDebug() << "5";
    lotro_progress_widget = new LotroProgressWidget(lotro_manager, settings, this);

    qDebug() << "Done. Adding to layouts";
    ui->content_layout->addWidget(export_widget);
    ui->content_layout->addWidget(import_widget);
    ui->content_layout->addWidget(manage_widget);
    ui->content_layout->addWidget(browse_widget);
    ui->content_layout->addWidget(lotro_progress_widget);
    lotro_progress_widget->hide();

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

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

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

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

    qDebug() << "Starting dat file initialisation";
    QMetaObject::invokeMethod(lotro_manager, "initialiseDatFile", Qt::QueuedConnection,
                              Q_ARG(QString, settings->value("advanced/dat_path").toString()));
    QMetaObject::invokeMethod(lotro_manager, "getUnactiveCategories", Qt::QueuedConnection);
}

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);
//        app->process_window->move(event->globalPos() - dragPosition +
//                                  QPoint((width() - app->process_window->width()) / 2, (height() - app->process_window->height()) / 2)
//                                  );
        event->accept();
    }
}

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

    ui->menu_widget->move(width * 675 / 2000, height * 80 / 1296);
    ui->menu_widget->resize(width * 1260 / 2000, height * 90 / 1296);

    ui->content_area->move(width * 25 / 2000, height * 250 / 1296);
    ui->content_area->resize(width * 1950 / 2000, height * 1000 / 1296);
    setupWindowBackgroundAndMask(current_bg);
}

void MainWindow::enableMenuItems()
{
    ui->menuentry_1_common->setEnabled(true);
    ui->menuentry_2_common->setEnabled(true);
    ui->menuentry_3_common->setEnabled(true);
    ui->menuentry_4_common->setEnabled(true);
}

void MainWindow::disableMenuItems()
{
    ui->menuentry_1_common->setEnabled(false);
    ui->menuentry_2_common->setEnabled(false);
    ui->menuentry_3_common->setEnabled(false);
    ui->menuentry_4_common->setEnabled(false);
}

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.scaled(size()));
    QPixmap *new_bg= new QPixmap(QPixmap(":/backgrounds/bg" + QString::number(next_pixmap_id) + ".png").scaled(size()));
    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_common_clicked()
{
    hideAllContentWidgets();
    manage_widget->show();
}

void MainWindow::on_menuentry_2_common_clicked()
{
    hideAllContentWidgets();
    export_widget->show();
}

void MainWindow::on_menuentry_3_common_clicked()
{
    hideAllContentWidgets();
    import_widget->show();
}

void MainWindow::on_menuentry_4_common_clicked()
{
    hideAllContentWidgets();
    browse_widget->show();
}

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

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

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

void MainWindow::onLotroManagerStarted(QString, QVector<QVariant>)
{
    hideAllContentWidgets();
    lotro_progress_widget->updateUI();
    lotro_progress_widget->show();
    disableMenuItems();
}

void MainWindow::onLotroManagerFinished(QString, QVector<QVariant>)
{
    hideAllContentWidgets();
    lotro_progress_widget->hide();

    emit MenuEntry::getActiveLabel()->clicked();
    if (lotro_manager->initialised())
        enableMenuItems();
}

void MainWindow::onLotroManagerErrorOccured(QString, QVector<QVariant> info) {
    QMessageBox::warning(nullptr, info[0].toString(), info[1].toString());
}

void MainWindow::makeConnections()
{
    connect(lotro_manager, &LotroDatManager::processStarted, this, &MainWindow::onLotroManagerStarted, Qt::QueuedConnection);
    connect(lotro_manager, &LotroDatManager::processFinished, this, &MainWindow::onLotroManagerFinished, Qt::QueuedConnection);
    connect(lotro_manager, &LotroDatManager::caughtError, this, &MainWindow::onLotroManagerErrorOccured, Qt::QueuedConnection);
}

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_common, &MenuEntry::hover_label_changed, this, &MainWindow::onHoverMenuentry);
    connect(ui->menuentry_2_common, &MenuEntry::hover_label_changed, this, &MainWindow::onHoverMenuentry);
    connect(ui->menuentry_3_common, &MenuEntry::hover_label_changed, this, &MainWindow::onHoverMenuentry);
    connect(ui->menuentry_4_common, &MenuEntry::hover_label_changed, this, &MainWindow::onHoverMenuentry);

    MenuEntry::setActiveLabel(ui->menuentry_1_common);
    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_common->raise();
    ui->menuentry_2_common->raise();
    ui->menuentry_3_common->raise();
    ui->menuentry_4_common->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()
{
    export_widget->hide();
    import_widget->hide();
    manage_widget->hide();
    browse_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("_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::on_closeButton_clicked()
{
    hide();
    qApp->quit();
}

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