#include "widgets/weeklycodewidget.h"
#include "ui_weeklycodewidget.h"
#include "weeklycodewidget.h"
#include <QApplication>
#include <QtConcurrent/QtConcurrent>
#include <QPainter>
#include <QPaintEvent>
#include <QClipboard>
#include "constants.h"
#include "models/settings.h"

WeeklyCodeWidget::WeeklyCodeWidget(QWidget *parent) :
    QWidget(parent), ui(new Ui::WeeklyCodeWidget)
{
    setAttribute(Qt::WA_Hover);
    setMouseTracking(true);
    ui->setupUi(this);
    ui->code->setText("загрузка...");
    code_data = "";

    code_downloader.targetBytearray = &code_data;
    code_downloader.setUrl(Settings::getValue("Network/weekly_code_url").toUrl());

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

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

void WeeklyCodeWidget::updateFontsSizes()
{
    ui->title->setFont(trajan_9pt);
    ui->code->setFont(trajan_10pt);
}

void WeeklyCodeWidget::resizeEvent(QResizeEvent *event)
{
    updateFontsSizes();
}

void WeeklyCodeWidget::enterEvent(QEvent * event)
{
    QWidget::enterEvent(event);
    event->ignore();
    if (QApplication::clipboard()->text() == ui->code->text())
        emit showCompletedTooltip();
    else
        emit showHelpTooltip();
}

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

void WeeklyCodeWidget::mouseReleaseEvent(QMouseEvent *ev)
{
    ui->code->setStyleSheet("color: rgb(255, 180, 0);");
    if (ui->code->text() != "загрузка...") {
        QApplication::clipboard()->setText(ui->code->text());
        emit showCompletedTooltip();
    }
    ev->ignore();
}

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

    ui->code->setText(code_data);
    repaint();
    code_data = "";
}

void WeeklyCodeWidget::leaveEvent(QEvent * event)
{
//    qDebug() << Q_FUNC_INFO << this->objectName();
    emit showNoTooltip();
}

