#pragma once
#include "actor.h"
#include "sensors/sensor.h"
#include <QVector>
#include <QString>
#include <QVariant>

class ScriptActor : public Actor
{
	Q_OBJECT
private:
	QVector<Sensor> sensors_;
	bool watchParentItem_ = false;
	QString scriptPath_;
	QString scriptCode_;

public:
	ScriptActor(QObject* parent = nullptr);
	virtual ~ScriptActor() {}

	void addSensor(const Sensor& sensor);
	void removeSensor(const Sensor& sensor);
	void clearSensors();
	QVector<Sensor> getSensors() const;

	void setWatchParentItem(bool watch);
	bool getWatchParentItem() const;

	void setScriptPath(const QString& path);
	QString getScriptPath() const;

	void setScriptCode(const QString& code);
	QString getScriptCode() const;

	// Run script manually (from editor) and return result
	QVariant runScriptNow();

public slots:
	void sensorEvent(Sensor sensor, sensor_update_type_t type);
	void onItemUpdated(ItemUpdateRequest update) override;

public:
	// Trigger an item update to sync configuration changes to primary instance
	void triggerSync();

	virtual QString getName() const override;
	virtual void store(QJsonObject& json) override;
	virtual void load(const QJsonObject& json, bool preserve) override;

private:
	QVariant runScriptInternal(const QVariantMap& triggerSource);
};