#include "tooltiplabel.h"
#include "ui_tooltiplabel.h"

#include <QtConcurrent/QtConcurrent>

TooltipLabel::TooltipLabel(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TooltipLabel)
{
    ui->setupUi(this);
    effect.setOpacity(0);
    setGraphicsEffect(&effect);
    QWidget::show();
    isHidden = true;
}

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

void TooltipLabel::show()
{
    isHidden = false;
    QtConcurrent::run([this](){
        const int iterations_num = 20;
        const int iteration_sleep = 10;

        for (int i = 0; i < iterations_num && qApp && !isHidden; ++i) {
            qreal opacity = double(i) / 20.0;
            effect.setOpacity(opacity);
            QMetaObject::invokeMethod(this, "updateOpacity", Qt::QueuedConnection, Q_ARG(qreal, opacity));
            QThread::msleep(iteration_sleep);
        }
    });
}

void TooltipLabel::hide()
{
    isHidden = true;
    QtConcurrent::run([this](){
        const int iterations_num = 20;
        const int iteration_sleep = 10;

        for (int i = iterations_num - 1; i >= 0 && qApp && isHidden; --i) {
            qreal opacity = double(i) / 20.0;
            QMetaObject::invokeMethod(this, "updateOpacity", Qt::QueuedConnection, Q_ARG(qreal, opacity));
            QThread::msleep(iteration_sleep);
        }
    });
}

void TooltipLabel::updateText(QString text)
{
    ui->label_small->setText(text);
}

void TooltipLabel::updateOpacity(double opacity)
{
    effect.setOpacity(opacity);
    setGraphicsEffect(&effect);
}
