#include "labelstimer.h"
#include <QTimer>

#include <QDebug>

LabelsTimer::LabelsTimer(QLabel *label, int time, QString format) :
    QObject(label),
    _label(label),
    _timer(new QTimer(label)),
    _time(time),
    _tempTime(time),
    _format(format)
{
    connect(_timer, &QTimer::timeout, this, &LabelsTimer::onTimeout);
}

LabelsTimer::~LabelsTimer()
{
    if(_timer != NULL) {
        delete _timer;
        _timer = NULL;
    }
}

void LabelsTimer::setLabel(QLabel *label)
{
    _label = label;
}

void LabelsTimer::start()
{
    _tempTime = _time;
    _timer->setInterval(1000);
    _timer->start();
    onTimeout();
    emit started();
}

void LabelsTimer::start(int time, QString format)
{
    _time = time;
    _format = format;
    start();
}

void LabelsTimer::stop()
{
    _tempTime = 0;
    _timer->stop();
    emit finished();
}

void LabelsTimer::onTimeout()
{
    if(_tempTime <= 1) {
        stop();
        emit timeout();
    } else {
        _label->setText(_format.arg(_tempTime));
        emit timeChanged(_tempTime);
        _tempTime = _tempTime - 1;
    }
}
