#include "statusflagwidget.h"
#include <QApplication>
#include <QtConcurrent/QtConcurrent>
#include <QPainter>
#include <QPaintEvent>
#include <QToolTip>

StatusFlagWidget::StatusFlagWidget(QWidget *parent) : QWidget(parent)
{
    setAttribute(Qt::WA_Hover);
    setMouseTracking(true);
    changeFlagId(3);
    changeImageSrcInstantly(current_flag_src);
}

void StatusFlagWidget::changeImageSrcAnimated(const QString &src)
{
    if (!qApp)
        return;

    QPixmap *cur_bg = new QPixmap(current_bg);
    QPixmap *new_bg= new QPixmap(QPixmap(src));

    QtConcurrent::run([cur_bg, new_bg, src, this](){
        const int iterations_num = 100;
        const int iteration_sleep = 20;

        for (int i = 0; i < iterations_num && qApp; i++) {
            if (!(is_hovered && current_flag_hover_src == src) && !(!is_hovered && current_flag_src == src))
                break;

            QPainter painter;
            painter.begin(cur_bg);
            painter.setOpacity(double(10 + i) / double(iterations_num));
            painter.setCompositionMode(QPainter::CompositionMode_Source);
            painter.drawPixmap(0,0, *new_bg);
            painter.end();
            bg_lock.lock();
            current_bg = *cur_bg;
            bg_lock.unlock();
            QMetaObject::invokeMethod(this, "repaint", Qt::QueuedConnection);
            QThread::msleep(iteration_sleep);
        }
        delete cur_bg;
        delete new_bg;
    });
}

void StatusFlagWidget::changeImageSrcInstantly(const QString &src)
{
    current_bg = QPixmap(src);
    repaint();
}

void StatusFlagWidget::changeFlagId(int new_flag_id)
{
    if (new_flag_id == flag_id)
        return;
    flag_id = new_flag_id;
    current_flag_src = ":/flags/flag" + QString::number(flag_id) + ".png";
    current_flag_hover_src = ":/flags/flag" + QString::number(flag_id) + "_hover.png";
    emit flagIdChanged(flag_id);
}

void StatusFlagWidget::enterEvent(QEvent * event)
{
    is_hovered = true;
    changeImageSrcAnimated(current_flag_hover_src);
    QWidget::enterEvent(event);
    event->ignore();
    emit mouseEntered("Нажмите, чтобы переключиться между новостями/текущими событиями и статусом серверов.");
}

void StatusFlagWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter;
    painter.begin(this);
    painter.drawPixmap(0,0, current_bg);
    painter.end();
}

void StatusFlagWidget::leaveEvent(QEvent * event)
{
    is_hovered = false;
    changeImageSrcAnimated(current_flag_src);
    QWidget::leaveEvent(event);
    event->ignore();
    emit mouseLeaved();
}

void StatusFlagWidget::mousePressEvent(QMouseEvent *ev)
{
    if (flag_id == 2) {
        changeFlagId(3);
        changeImageSrcInstantly(current_flag_hover_src);
    } else {
        changeFlagId(2);
        changeImageSrcInstantly(current_flag_hover_src);
    }
    QWidget::mousePressEvent(ev);
}
