#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),
    _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()
{
    _label->setText(_format.arg(_time));
    _timer->setInterval(1000);
    _timer->start();
}

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

void LabelsTimer::stop()
{
    _timer->stop();
}

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