#include "alarmtime.h"

AlarmTime::AlarmTime(const QDateTime time, QObject *parent) : Actor(parent), time_(time)
{
	connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
	timer.setInterval(1000);
	AlarmTime::run();
}

AlarmTime::~AlarmTime()
{
	AlarmTime::makeInactive();
}

void AlarmTime::run()
{
	AlarmTime::makeInactive();

	active = true;
	timer.start();
}

void AlarmTime::makeActive()
{
	run();
}

QString AlarmTime::getName() const
{
	if(name_.size() > 0)return  name_;
	else
	{
		QString string;
		string = "Alarm: ";
		if(repeat_ == REPEAT_DAILY)
		{
			string.append("daily ");
			string.append(time_.toString("HH:mm"));
		}
		else if(repeat_ == REPEAT_WEEKLY)
		{
			string.append("weekly ");
			string.append(time_.toString("ddd HH:mm"));

		}
		else if(repeat_ == REPEAT_MONTHLY)
		{
			string.append("monthly ");
			string.append(time_.toString("dd HH:mm"));
		}
		else if(repeat_ == REPEAT_YEARLY)
		{
			string.append("yearly ");
			string.append(time_.toString("dd.mm HH:mm"));

		}
		else string.append(time_.toString("dd.mm.yyyy HH:mm"));
		return string;
	}
}

void AlarmTime::setRepeat(const uint8_t repeat)
{
	repeat_ = repeat;
	exausted = false;
}

uint8_t AlarmTime::getRepeat()
{
	return repeat_;
}

QDateTime AlarmTime::getDateTime()
{
	return time_;
}

void AlarmTime::makeInactive()
{
	timer.stop();
	active = false;
}

void AlarmTime::doTick()
{
	if(
	    (
	        (triggerd_ == false)                                                                                           &&
	        (time_.date().year()  == QDate::currentDate().year()  || repeat_ != REPEAT_NEVER)                              &&
	        (time_.date().month() == QDate::currentDate().month() || repeat_ == REPEAT_MONTHLY || repeat_ == REPEAT_DAILY) &&
	        (time_.date().day()   == QDate::currentDate().day()   || repeat_ == REPEAT_DAILY)
	    )
	    ||
	    (
	        (repeat_ == REPEAT_WEEKLY) &&
	        (time_.date().dayOfWeek() == QDate::currentDate().dayOfWeek())
	    )
	)
	{
		if(time_.time().hour() == QTime::currentTime().hour() && time_.time().minute() == QTime::currentTime().minute())
		{
			triggerd_=true;
			performAction();
			if(repeat_ == REPEAT_NEVER) exausted = true;
		}
	}
	else if( repeat_ != REPEAT_NEVER && time_.time().hour() != QTime::currentTime().hour() ) triggerd_=false;
}

void AlarmTime::changeTime(const QDateTime& time)
{
	time_=time;
	exausted = false;
	qDebug()<<"time: "<<time_;
}


void AlarmTime::store(QJsonObject& json)
{
	json["Type"] = "Alarm";
	Actor::store(json);
	json["Time"] = time_.toString();
	json["Repeat"] = repeat_;
}

void AlarmTime::load(const QJsonObject& json, const bool preserve)
{
	bool oldActive = isActive();
	Actor::load(json, preserve);
	time_ = QDateTime::fromString(json["Time"].toString(""));
	repeat_ = json["Repeat"].toInt(REPEAT_NEVER);
	if(oldActive != isActive()) setActive(isActive());
}
