#ifndef SH_RUNTIME_H
#define SH_RUNTIME_H

#include "SH_types.h"
#include <QQmlEngine>
#include <qpiconnection.h>

#define RUNTIME (SHRuntime::instance())


class ScriptCache {
public:
	ScriptCache();
	void build(SHS::Object & o, const QString & root = QString());
	void clear();
	QMap<uint, SHS::Command*> command_by_id;
	QMap<uint, SHS::Object*> object_by_id;
	QHash<QString, QVector<SHS::Command*> > commands_in;
private:
	void buildInternal(SHS::Object & o, QStringList path);
	SHS::Object * root_;
	uint cmd_id_, obj_id_;
};


class SHRuntime: public QObject {
	Q_OBJECT
public:
	SHRuntime();
	~SHRuntime();

	static SHRuntime * instance();

	struct Block {
		Block(QObject * o) {
			object = o;
		}
		~Block() {
			if (object)
				delete object;
			object = 0;
		}
		QObject * object;
		QHash<QString, QStringList> packet_vars_aliases; // [source_var] = aliases
	};

	void setServerData(const SHS::ServerData & d);
	void openFromCmdFile();

	QQmlEngine * engine_ = nullptr;
	SHSScriptEngineBase * shs_engine_ = nullptr;
	SHPluginsManager * plugins_manager = nullptr;
	ScriptCache cache;
	SHS::ServerData server_data;
	SHS::ServerProject server_project;
	QString shs_file, shs_db_file;
	QPIConnection connection;
	QList<SHS::ScriptVariable> variables;
	QObjectList widget_list;
	QMap<uint, PropertyStorage> plugins_props_global, plugins_props_project;
	QByteArray json_ui, json_diff;
	double font_scale = 1.;
	bool is_test = false; // true if server designer test

signals:
	void invokeCommand(SHS::Command * cmd, QVariantList args, QVariant * ret);
	void sendBroadcast(QByteArray data);

};

#endif // SH_RUNTIME_H
