#include <QTcpSocket>
#include <QJsonDocument>
#include <QJsonArray>

#include "items/item.h"
#include "items/itemstore.h"
#include "service.h"


Service::Service(QObject* parent):
	ItemSource(parent)
{}

QJsonObject Service::createMessage(const QString& type, const QJsonArray& data)
{
	QJsonObject json;
	json["MessageType"] = type;
	json["Data"] = data;
	return json;
}

void Service::sensorEvent(Sensor sensor, sensor_update_type_t type)
{
	QJsonArray sensors;
	QJsonObject sensorjson;
	sensor.store(sensorjson);
	sensors.append(sensorjson);
	QJsonObject json = createMessage("SensorUpdate", sensors);
	sendJson(json);
}

void Service::itemUpdated(ItemUpdateRequest update) {}

void Service::addSensor(Sensor sensor, Sensor::sensor_backend_type_t backend, QJsonObject payload)
{
	QJsonObject sensorjson;
	sensor.store(sensorjson);
	QJsonObject json = createMessage("AddSensor", QJsonArray());
	json["Sensor"] = sensorjson;
	json["Backend"] = static_cast<int>(backend);
	json["Payload"] = payload;
	sendJson(json);
}

void Service::refresh()
{
	sendJson(createMessage("GetSensors", QJsonArray()));
	sendJson(createMessage("GetItems", QJsonArray()));
}

void Service::sendSensors()
{
	QJsonArray sensors;
	for(auto& sensor: *globalSensors.getSensors())
	{
		QJsonObject sensorjson;
		sensor.store(sensorjson);
		sensors.append(sensorjson);
	}
	sendJson(createMessage("SensorUpdate", sensors));
}

void Service::sendItems()
{
	QJsonArray items;
	for(auto& item: *globalItems.getItems())
	{
		QJsonObject itemjson;
		item->store(itemjson);
		items.append(itemjson);
	}
	QJsonObject json = createMessage("ItemUpdate", items);
	json["FullList"] = true;
	sendJson(json);
}

void Service::processIncomeingJson(const QByteArray& jsonbytes)
{
	QJsonDocument doc = QJsonDocument::fromJson(jsonbytes);
	QJsonObject json = doc.object();
	QString type = json["MessageType"].toString();
	if(type == "GetSensors")
	{
		qDebug()<<"Sending sensors";
		sendSensors();
	}
	else if(type == "GetItems")
	{
		qDebug()<<"Sending Items";
		sendItems();
	}
	else if(type == "SensorUpdate")
	{
		QJsonArray data = json["Data"].toArray();
		for(QJsonValueRef sensorjson : data)
		{
			QJsonObject jsonobject = sensorjson.toObject();
			Sensor sensor(jsonobject);
			gotSensor(sensor, SENSOR_UPDATE_REMOTE);
		}
	}
	else if(type == "AddSensor")
	{
		QJsonObject sensorjson = json["Sensor"].toObject();
		Sensor sensor(sensorjson);
		Sensor::sensor_backend_type_t backend = static_cast<Sensor::sensor_backend_type_t>(json["Backend"].toInt(0));
		QJsonObject payload = json["Payload"].toObject();
		emit sensorAdded(sensor, backend, payload);
	}
}
