#include "polynomalactor.h"

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

}

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

}

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


void PolynomalActor::setCoeffiancts( const double pow3, const double pow2, const double pow1, const double pow0 )
{
	pow3_=pow3;
	pow2_=pow2;
	pow1_=pow1;
	pow0_=pow0;
}
void PolynomalActor::getCoeffiancts( double& pow3, double& pow2, double& pow1, double& pow0 )
{
	pow3=pow3_;
	pow2=pow2_;
	pow1=pow1_;
	pow0=pow0_;
}

void PolynomalActor::sensorEvent(Sensor sensor, sensor_update_type_t type)
{
	if(active && sensor == sensor_)
	{
		double result = pow3_*(sensor.field*sensor.field*sensor.field)+pow2_*(sensor.field*sensor.field)+pow1_*sensor.field
		                +pow0_;
		if(result < 0) result = 0;
		else if(result > 254) result = 255;
		if(result != prevValue)
			performValueAction(static_cast<uint8_t>(result));
		prevValue = result;
	}
}

void PolynomalActor::store(QJsonObject& json)
{
	json["Type"] = "Polynomal";
	Actor::store(json);
	json["Pow3"] = pow3_;
	json["Pow2"] = pow2_;
	json["Pow1"] = pow1_;
	json["Pow0"] = pow0_;
	json["SensorType"] = static_cast<int>(sensor_.type);
	json["SensorId"] = static_cast<int>(sensor_.id);
	json["SensorField"] = sensor_.field;
	json["SensorName"] = sensor_.name;
}

void PolynomalActor::load(const QJsonObject& json, bool preserve)
{
	Actor::load(json, preserve);
	pow3_ = json["Pow3"].toDouble(0);
	pow2_ = json["Pow2"].toDouble(0);
	pow1_ = json["Pow1"].toDouble(1);
	pow0_ = json["Pow0"].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 PolynomalActor::getName() const
{
	if(name_.size() > 0) return name_;
	else
	{
		QString string;
		string = QString::number(pow3_) + "x^3 + " + QString::number(pow2_) + "x^2 + " + QString::number(
		             pow1_) + "x + " + QString::number(pow0_) + " (x: " + sensor_.name + ")";
		return string;
	}
}

