#include "regulator.h"

#include <QDebug>

Regulator::Regulator(const Sensor sensor, QObject* parent): Actor(parent), sensor_(sensor)
{
	timer.setSingleShot(true);
	timer.start(timeout_*1000);
	connect(&timer, &QTimer::timeout, this, &Regulator::timeout);
}

Regulator::Regulator(QObject* parent): Actor(parent)
{
	timer.setSingleShot(true);
	timer.start(timeout_*1000);
	connect(&timer, &QTimer::timeout, this, &Regulator::timeout);
}

void Regulator::setSensor(const Sensor sensor)
{
	sensor_ = sensor;
}

void Regulator::sensorEvent(Sensor sensor, sensor_update_type_t type)
{
	if(active && sensor == sensor_)
	{
		timer.start(timeout_*1000);
		if( sensor.field < setPoint_-band_ && (sensor.field < sensor_.field || sensor_.field > setPoint_-band_ || first) )
		{
			performValueAction(triggerValue);
		}
		else if( sensor.field > setPoint_+band_ && (sensor.field > sensor_.field || sensor_.field < setPoint_+band_ || first) )
		{
			performValueAction(!triggerValue);
		}
		first = false;
		sensor_ = sensor;
	}
}

void Regulator::makeInactive()
{
	first = true;
	performValueAction(!triggerValue);
	timer.stop();
	Actor::makeInactive();
}

void Regulator::timeout()
{
	performValueAction(safeValue_);
}

void Regulator::setPoint(float setPoint)
{
	setPoint_ = setPoint;
}

void Regulator::setBand ( float band )
{
	band_ = band;
}

void Regulator::setInvert( bool invert )
{
	invert_ = invert;
}

void Regulator::setSafeValue(int value)
{
	safeValue_ = value;
}

void Regulator::setTimeout(int value)
{
	timeout_ = value;
	timer.start(timeout_*1000);
}

void Regulator::store(QJsonObject& json)
{
	json["Type"] = "Regulator";
	Actor::store(json);
	json["Band"] = band_;
	json["SetPoint"] = setPoint_;
	json["SafeValue"] = safeValue_;
	json["Timeout"] = timeout_;
	json["SensorType"] = static_cast<int>(sensor_.type);
	json["SensorId"] = static_cast<int>(sensor_.id);
	json["SensorField"] = sensor_.field;
	json["SensorName"] = sensor_.name;
}

void Regulator::load(const QJsonObject& json, bool preserve)
{
	Actor::load(json, preserve);
	band_ = json["Band"].toDouble(1);
	setPoint_ = json["SetPoint"].toDouble(22);
	safeValue_ = json["SafeValue"].toDouble(0);
	timeout_ = json["Timeout"].toDouble(1800);
	sensor_.type = static_cast<Sensor::sensor_type_t>(json["SensorType"].toInt(0));
	sensor_.id = json["SensorId"].toInt(0);
	sensor_.field = json["SensorField"].toInt(0);
	sensor_.name = json["SensorName"].toString("Sensor");
	timer.start(timeout_*1000);
}

QString Regulator::getName() const
{
	if(name_.size() > 0)
	{
		return name_;
	}
	else
	{
		QString string;
		string = "Regulate \"" + sensor_.name + "\" to ";
		string.append(QString::number(setPoint_) + " ");
		return string;
	}
}
