#include "weeklycodewidget.h"
#include <QApplication>
#include <QtConcurrent/QtConcurrent>
#include <QPainter>
#include <QPaintEvent>
#include <QClipboard>

WeeklyCodeWidget::WeeklyCodeWidget(QWidget *parent) : QLabel(parent)
{
    setAttribute(Qt::WA_Hover);
    setMouseTracking(true);
    current_bg = QPixmap(":/buttons/lotr_circle.png").scaled(130, 130);
    changeImageSrc(":/buttons/lotr_circle.png");
    setText("ЗАГРУЗКА");
    code_data = "";

    code_downloader.targetBytearray = &code_data;
    code_downloader.setUrl(QUrl("http://translate.lotros.ru/coupon.txt"));

    connect(&code_update_timer, &QTimer::timeout, &code_downloader, &Downloader::start);
    connect(&code_downloader, &Downloader::downloadFinished, this, &WeeklyCodeWidget::updateCode, Qt::QueuedConnection);
    emit code_downloader.start();
    code_update_timer.setInterval(1000 * 60); // 1 minute;
    code_update_timer.start();
}

void WeeklyCodeWidget::changeImageSrc(const QString &src)
{
    if (!qApp)
        return;

    img_src = src;
    QPixmap *cur_bg = new QPixmap(current_bg.scaled(130, 130));
    QPixmap *new_bg= new QPixmap(QPixmap(src).scaled(130, 130));

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

        for (int i = 0; i < iterations_num && qApp; i++) {
            if (img_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 WeeklyCodeWidget::enterEvent(QEvent * event)
{
    changeImageSrc(":/buttons/lotr_circle_hover.png");
    QWidget::enterEvent(event);
    event->ignore();
    emit mouseEntered("<a href='http://www.lotro-mindon.ru/content/kak-poluchit-ezhenedelnyy-podarok'>Код недели.</a>\nНажмите, чтобы скопировать в буфер обмена");
}

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

void WeeklyCodeWidget::mousePressEvent(QMouseEvent *ev)
{
    setStyleSheet("color: rgb(255, 150, 0);");
    ev->ignore();
}

void WeeklyCodeWidget::mouseReleaseEvent(QMouseEvent *ev)
{
    setStyleSheet("color: rgb(255, 180, 0);");
    QApplication::clipboard()->setText(text());
    ev->ignore();
}

void WeeklyCodeWidget::updateCode()
{
    qDebug() << "New code: " << code_data;
    if (code_data.isEmpty())
        return;

    setText(code_data);
    repaint();
    code_data = "";
}

void WeeklyCodeWidget::leaveEvent(QEvent * event)
{
    qDebug() << Q_FUNC_INFO << this->objectName();
    changeImageSrc(":/buttons/lotr_circle.png");
    emit mouseLeaved();
}

