#include "timeractor.h"
#include <QDebug>

TimerActor::TimerActor(const int timeoutSec, QObject *parent): Actor(parent), timeoutMsec_(timeoutSec*1000)
{
	connect(&timer, &QTimer::timeout, this, &TimerActor::timeout);
	timer.setSingleShot(true);
}

void TimerActor::onItemUpdated(ItemUpdateRequest update)
{
	if(update.changes.value && ((update.payload.getValue() && !triggerValue) || (!update.payload.getValue() && triggerValue)))
	{
		qDebug()<<"Timer started";
		if(timer.isActive())
			timer.stop();
		timer.setInterval(timeoutMsec_);
		timer.start();
	}
}

void TimerActor::store(QJsonObject& json)
{
	json["Type"] = "Timer";
	Actor::store(json);
	json["Timeout"] = timeoutMsec_;
}

void TimerActor::load(const QJsonObject& json, bool preserve)
{
	Actor::load(json, preserve);
	timeoutMsec_ = json["Timeout"].toInt(10000);
}

void TimerActor::setTimeout(const int timeoutSec)
{
	timeoutMsec_ = timeoutSec*1000;
}

int TimerActor::getTimeout()
{
	return timeoutMsec_/1000;
}

void TimerActor::timeout()
{
	performAction();
}

QString TimerActor::getName() const
{
	if(name_.size() > 0) return name_;
	else
	{
		QString string;
		string = "Timeout after " + QString::number(timeoutMsec_/1000) + " seconds. ";
		return string;
	}
}
