#include "sensoractor.h"

#include <QDebug>

SensorActor::SensorActor(const Sensor sensor, QObject* parent): Actor(parent), sensor_(sensor)
{

}

SensorActor::SensorActor(QObject* parent): Actor(parent)
{

}

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

void SensorActor::sensorEvent(Sensor sensor, sensor_update_type_t type)
{
	if(sensor == sensor_)
	{
		if((sloap_ == SLOPE_UP || sloap_ == SLOPE_BOTH) && sensor_.field < threshold_
		        && sensor.field >= threshold_ )  performAction();
		else if((sloap_ == SLOPE_DOWN || sloap_ == SLOPE_BOTH) && sensor_.field > threshold_
		        && sensor.field <= threshold_)  performAction();
		sensor_ = sensor;
	}
}

void SensorActor::setSloap(uint8_t sloap)
{
	sloap_=sloap;
}

void SensorActor::setThreshold(float threshold)
{
	threshold_ = threshold;
}

float SensorActor::getThreshold()
{
	return threshold_;
}
uint8_t SensorActor::getSloap()
{
	return sloap_;
}

void SensorActor::store(QJsonObject& json)
{
	json["Type"] = "Sensor";
	Actor::store(json);
	json["Sloap"] = sloap_;
	json["Threshold"] = threshold_;
	json["SensorType"] = static_cast<int>(sensor_.type);
	json["SensorId"] = static_cast<int>(sensor_.id);
	json["SensorField"] = sensor_.field;
	json["SensorName"] = sensor_.name;
}

void SensorActor::load(const QJsonObject& json, bool preserve)
{
	Actor::load(json, preserve);
	sloap_ = json["Sloap"].toInt(0);
	threshold_ = json["Threshold"].toDouble(0);
	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");
}

QString SensorActor::getName() const
{
	if(name_.size() > 0) return name_;
	else
	{
		QString string;
		string = "Sensor \"" + sensor_.name + "\"";

		if(sloap_ == SLOPE_UP) string.append(" rises to ");
		else if (sloap_ == SLOPE_DOWN) string.append(" drops to ");
		else if (sloap_ == SLOPE_BOTH) string.append(" passes ");

		string.append(QString::number(threshold_) + " ");
		return string;
	}
}
