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

#include "alarmtime.h"
#include "sensoractor.h"
#include "timeractor.h"
#include "regulator.h"
#include "polynomalactor.h"
#include "scriptactor.h"

Actor::Actor(QObject *parent): Item(QRandomGenerator::global()->generate(), "", 0, parent)
{
}

Actor::~Actor()
{

}

void Actor::performValueAction(uint8_t value)
{
	if(active)
	{
		ItemUpdateRequest request;
		request.type = ITEM_UPDATE_ACTOR;
		request.payload = ItemData(QRandomGenerator::global()->generate(), "Item", value);
		request.changes.value = true;
		sigItemUpdate(request);
	}
}

void Actor::performAction()
{
	performValueAction(triggerValue);
}

void Actor::makeActive()
{
	active = true;
}


void Actor::makeInactive()
{
	active = false;
}

QString Actor::actionName()
{
	QString string;
	if(triggerValue == 0 )
		string = "off";
	else if(triggerValue == 1 )
		string = "on";
	else
		string = "value to " + QString::number(triggerValue);
	return  string;
}

void Actor::setActive(uint8_t state)
{
	state ? makeActive() : makeInactive();
}

bool Actor::isActive()
{
	return active;
}

bool Actor::isExausted()
{
	return exausted;
}

void Actor::store(QJsonObject& json)
{
	Item::store(json);
	json["Active"] =  active;
	json["Exausted"] = exausted;
	json["TriggerValue"] = triggerValue;
}

void Actor::load(const QJsonObject& json, const bool preserve)
{
	Item::load(json, preserve);
	active = json["Active"].toBool();
	exausted = json["Exausted"].toBool();
	triggerValue = json["TriggerValue"].toInt();
}

void Actor::setTriggerValue(uint8_t value)
{
	triggerValue=value;
}

uint8_t Actor::getTriggerValue()
{
	return  triggerValue;
}

void Actor::onItemUpdated(ItemUpdateRequest update)
{
	(void) update;
}

std::shared_ptr<Actor> Actor::createActor(const QString& type)
{
	std::shared_ptr<Actor> actor;
	if(type == "Alarm") actor = std::shared_ptr<Actor>(new AlarmTime());
	else if(type == "Sensor") actor = std::shared_ptr<Actor>(new SensorActor());
	else if(type == "Timer") actor = std::shared_ptr<Actor>(new TimerActor());
	else if(type == "Regulator") actor = std::shared_ptr<Actor>(new Regulator());
	else if(type == "Polynomal") actor = std::shared_ptr<Actor>(new PolynomalActor());
	else if(type == "Script") actor = std::shared_ptr<Actor>(new ScriptActor());
	else if(type == "Actor") actor = std::shared_ptr<Actor>(new Actor());
	return actor;
}

std::shared_ptr<Actor> Actor::loadActor(const QJsonObject &json)
{
	QString type = json["Type"].toString("Actor");
	std::shared_ptr<Actor> actor = createActor(type);
	if(actor) actor->load(json);
	return actor;
}

void Actor::enactValue(uint8_t value)
{
	setActive(value);
}
