#include "plugin_MainServer.h"
#include <QApplication>
#include <QFileInfo>
#include <qvariantedit.h>
#include "piqt_connection_edit.h"
#include "SH_network_types.h"


MainServerPlugin::MainServerPlugin() {
	Q_INIT_RESOURCE(plugin_MainServer);
}


PropertyStorage MainServerPlugin::addProperties(const BlockItem * block, PropertyStorage cur_props) {
	PropertyStorage ret;
	QAD::File ft;
	ft.is_abs = false;
	ft.file = "server_designer";
	ret << BlockItem::Property("server designer", "Server designer path", QVariant::fromValue<QAD::File>(ft), SHS::Hidden | SHS::Fixed);
	ft.is_save = true;
	ft.file = "";
	ft.filter = "Server Designer project(*.sdp)";
	ret << BlockItem::Property("project file", "Server designer project", QVariant::fromValue<QAD::File>(ft));
	ret << BlockItem::Property("_connection_", "QPIConnection, for internal use only", QByteArray(), SHS::Internal | SHS::Hidden);
	//ft.filter = "Connection model (*.cm)";
	//ret << BlockItem::Property("_connection_file_", "QPIConnection, for internal use only", QVariant::fromValue<QAD::File>(ft), SH_Designer::Internal | SH_Designer::Hidden | SH_Designer::InstallFileWatcher);
	return ret;
}


PropertyStorage MainServerPlugin::addPropertiesToProject() const {
	PropertyStorage ret;
	ret.addProperty("cloud_enabled", false, "PICloud dispatcher enable");
	ret.addProperty("cloud_address", QString("shs.tools:%1").arg(SHNetworkTypes::cloudPort), "PICloud dispatcher address (host:port)");
	return ret;
}


QList<SHPluginBase::PluginAction> MainServerPlugin::addActions(const BlockItem * block) {
	QList<PluginAction> actions;
	actions << PluginAction("edit", "Edit server", GenerateDatabase | CloseDialog | ApplyProperties, EditIcon,
							{}, "Run Server Designer");
	actions << PluginAction("conn", "Edit connections", ApplyProperties, CustomIcon,
							QIcon(":/icons/piconnection.png"), "Run Connection Editor");
	actions << PluginAction("create_conn", "Auto connection", ApplyProperties, CustomIcon,
							QIcon(":/icons/quickopen.png"), "Automaticaly create connections");
	actions << PluginAction("generate_db", "Generate DB", GenerateDatabase | CloseDialog, ConfigureIcon);
	return actions;
}


void MainServerPlugin::runAction(BlockItem * block, const PluginAction & action, const PropertyStorage & proj_props) {
	if (action.name == "edit") {
		QString cmd = block->propertyByName("server designer").value.value<QAD::File>().file;
		QAD::File prof_qf = block->propertyByName("project file").value.value<QAD::File>();
		QString file = prof_qf.file;
		if (file.isEmpty()) {
			file = proj_props.propertyValueByName("name").toString() + ".sdp";
			prof_qf.file = file;
			block->setPropertyValue("project file", QVariant::fromValue(prof_qf));
		} else {
			if (!file.endsWith(".sdp"))
				file += ".sdp";
		}
		//qDebug() << file << generatedDatabaseFile(block);
		QProcess::startDetached(findExecutable(cmd), {file, "-shs", runtime()->shs_file, "-shs_db", runtime()->shs_db_file});
	}
	if (action.name == "conn") {
		QString file = block->propertyByName("project file").value.value<QAD::File>().file;
		if (!file.endsWith(".sdp")) file += ".sdp";
		BlockItem::Property pconn = block->propertyByName("_connection_");
		runConnectionEdit(block, pconn.value.toByteArray());
	}
	if (action.name == "create_conn") {
		runConnectionEdit(block, SHS::blockConnectionModel(block));
	}
}


QString MainServerPlugin::generatedDatabaseFile(const BlockItem * block) {
	QString f = block->propertyByName("project file").value.value<QAD::File>().file;
	f.chop(QFileInfo(f).completeSuffix().size());
	if (f.endsWith(".")) f.chop(1);
	return (f + ".dat");
}


QString MainServerPlugin::generatedConnectionFile(const BlockItem * block) {
	QString f = block->propertyByName("project file").value.value<QAD::File>().file;
	f.chop(QFileInfo(f).completeSuffix().size());
	if (f.endsWith(".")) f.chop(1);
	return (f + ".cm");
}


void MainServerPlugin::checkBlock(BlockItem * block) {
	QString cmd = block->propertyByName("server designer").value.value<QAD::File>().file;
	if (cmd.isEmpty())
		emitMessage(SHS::mcWarning, tr("\"server designer\" property is empty! Fix it in database!"));
}


bool MainServerPlugin::checkAction(const BlockItem * block, const PluginAction & action) {
	/*if (action.name == "edit") {
		QString file = block->propertyByName("project file").value.value<QAD::File>().file;
		return !file.isEmpty();
	}*/
	return true;
}


QList<BlockType> MainServerPlugin::createBlockTypes() {
	BlockType block;
	block.name = "SHS-MS-1";
	block.description = "Main server";
	block.block_plugin = "Main SHS server";
	block.properties.addProperty("id", 1);
	block.properties.addProperty("name", "sh_MS");
	block.properties.addProperty("USB Host", true, "", SHS::Fixed | SHS::Hidden);
	block.model = readFile(":/MainServer.blockmodel");
	block.flags = SHS::Computer;
	configurePin(block, "Eth", "Ethernet");
	configurePin(block, "485", "RS-485");
	configurePin(block, "USB0", "USB");
	configurePin(block, "USB1", "USB");
	configurePin(block, "USB2", "USB");
	configurePin(block, "USB3", "USB");
	block.pins_properties["485"].addProperty("device", "ser://");
	QAD::Enum usbver;
	usbver << "USB 1.1" << "USB 2.0" << "USB 3.0";
	usbver.selectValue(1);
	for (int i = 0; i < 4; ++i) {
		block.pins_properties[QString("USB%1").arg(i)].addProperty("USB Version", QVariant::fromValue<QAD::Enum>(usbver), "", SHS::Fixed);
	}
	return {block};
}


void MainServerPlugin::runConnectionEdit(BlockItem * block, const QByteArray & model) {
	ConnectionEdit ce;
	ce.setModel(model);
	if (ce.exec() == QDialog::Accepted) {
		BlockItem::Property pconn = block->propertyByName("_connection_");
		pconn.value = ce.model();
		block->addProperty(pconn);
		//getConnPathes(ce.model());
		//writeConnectionFile(block, block->propertyByName("_connection_file_").value.value<QAD::File>().file);
	}
}
