#ifndef CANCONTROLLER_H
#define CANCONTROLLER_H

#include <QObject>
#include <QVariant>
#include <QDateTime>

#include "BatteryController.h"

class QQmlEngine;
class QJSEngine;
class QTimer;

class CanId;
class CanMessage;

class CanController : public QObject
{
	Q_OBJECT

	Q_PROPERTY(bool isConnected MEMBER isConnected_ NOTIFY isConnectedChanged)
	Q_PROPERTY(QList<BatteryController*> batteries MEMBER batteries_ NOTIFY batteriesChanged)

public:
	explicit CanController(QObject* parent = nullptr);
	~CanController();

	static QObject* qmlInstance(QQmlEngine* engine, QJSEngine* scriptEngine);

public slots:
	void connectCan();
	void disconnectCan();
	void tryConnectCan();

	void sendCanMessage(const CanMessage& message, bool highPriority = false);
	void sendMessages();

	void requestParameters();
	void setBatteryAction();

signals:
	void isConnectedChanged();
	void batteriesChanged();

private slots:
	void handlePackage(int index);

	void handleControlParameters(const CanMessage* message, qsizetype batteryIndex);
	void handleMeasuredParameters(const CanMessage* message, qsizetype batteryIndex);
	void handleStatusParameters(const CanMessage* message, qsizetype batteryIndex);

	void updateCanStatus();

private:
	void setupDrivers();
	void saveConfiguration();
	void initializeBatteries();

	QList<quint16> registerAddresses() const;
	QVariant parameterToVariant(quint16 parameter) const;

private:
	bool isConnected_ = false;
	bool isFirstCheck_ = true;
	QDateTime lastPackageDateTime_;
	QList<CanMessage> sendMessages_;

	QList<BatteryController*> batteries_;
};

#endif // CANCONTROLLER_H
