#ifndef MICROCONTROLLER_H
#define MICROCONTROLLER_H

#include <QObject>
#include <QColor>
#include <QIODevice>
#include <QString>
#include <QRunnable>
#include <QDebug>
#include <QTimer>
#include <QByteArray>
#include <QQueue>
#include <vector>
#include <memory>
#include "items/item.h"
#include "items/relay.h"
#include "sensors/sensor.h"
#include "items/itemsource.h"

class Microcontroller : public ItemSource
{

	Q_OBJECT

public:

	static constexpr char AMP_RELAY = 0;
	static constexpr char SENSOR_TEMPERATURE = 1;
	static constexpr char SENSOR_DOOR = 0 ;

private:

	bool listMode = false;

	QIODevice* _port = nullptr;
	QQueue<QByteArray> writeQue;
	QTimer writeTimer;

	std::vector< std::shared_ptr<Item> > relayList;

	QString _buffer;

	void processMicroReturn();
	void processList(const QString& buffer);
	void processRelayState(const QString& buffer);
	void processSensorState(const QString& buffer);
	std::shared_ptr<Relay> processRelayLine(const QString& buffer);

	void write(char *buffer, const size_t length);
	void write(const QByteArray& buffer);

public:
	Microcontroller(QIODevice* port);
	Microcontroller();
	~Microcontroller();
	bool connected();
	void setIODevice(QIODevice* port);

public slots:
	void rgbOn();
	void rgbOff();
	void changeRgbColor(const QColor color);
	void setPattern(int pattern);
	void startSunrise();

	void refresh() override;

	void setAuxPwm(int duty);

	void relayOn(int relay);
	void relayOff(int relay);
	void relayToggle(int state, int id);

private slots:

	void isReadyRead();
	void onWriteTimerTimeout();

signals:
	void textRecived(const QString string);
	void gotSensorState(Sensor sensor, sensor_update_type_t type = SENSOR_UPDATE_BACKEND);
};

#endif // MICROCONTROLLER_H
