//版本:2.0.0

//DBus
var DBus = require('/app/Web/node_modules/DBus');
var Bus = DBus.getBus('session');
var iftttmaker=require('./node_modules/iftttmaker');
var fs = require("fs");








//OK
function IsDioRangeValue(LowerLimitValue, TargetValue, UpperLimitValue)
{
	var Return=false;
	if(TargetValue<=UpperLimitValue && TargetValue>=LowerLimitValue)
	{
		Return=true;
	}
	return Return;
}
//OK
function IsAioRangeValue(LowerLimitValue, TargetValue, UpperLimitValue)
{
	var Return=false;
	if(TargetValue<UpperLimitValue && TargetValue>LowerLimitValue)
	{
		Return=true;
	}
	return Return;
}
//OK
function IsDioConditionsTrigger(Data, Value)
{
	var UpperLimitValue    =Data["UpperLimitValue"];
	var LowerLimitValue    =Data["LowerLimitValue"];
	var Return=false;
	if(Data["Condition"] == "StatusChange")
	{
		if(IsDioRangeValue(LowerLimitValue, Value, UpperLimitValue) == false && Data["SwitchValue"]==true)
		{
			if(Value==0)
			{
				Data["UpperLimitValue"]=0;
				Data["LowerLimitValue"]=0;
			}
			else
			{
				Data["UpperLimitValue"]=1;
				Data["LowerLimitValue"]=1;
			}
			Return=true;
		}
	}
	return Return;
}
//OK
function IsAioConditionsTrigger(Data, Value)
{
	var UpperLimitValue    =Data["UpperLimitValue"];
	var LowerLimitValue    =Data["LowerLimitValue"];
	var TargetValue        =Data["Condition"].split(":")[0];
	TargetValue=TargetValue.replace("=","");
	TargetValue=parseFloat(TargetValue);
	var Return=false;
	
	if(IsAioRangeValue(LowerLimitValue, Value, UpperLimitValue) == false && Data["SwitchValue"]==true)
	{
		Data["UpperLimitValue"]=Value+Data["Deadband"];
		Data["LowerLimitValue"]=Value-Data["Deadband"];
		Return=true;
	}
	else if(IsAioRangeValue(LowerLimitValue, Value, UpperLimitValue) == true && Data["SwitchValue"]==false)
	{
	}
	return Return;
}
//OK
function SendMessage(Event, Key, SendString)
{
	var IFTTTMaker = iftttmaker(Key);
	IFTTTMaker.send(Event, SendString, function (error)
	{
		if (error) 
		{
				console.log('The request could not be sent:', error);
		} else
		{
				console.log('Request was sent');
		}
	});
}
//OK
function LoopJudgment(BusInterface, RuntimeVariable, Data)
{
	if(typeof(BusInterface) == "undefined")	{return 0;}
	BusInterface.ReadVariantArray(RuntimeVariable, {timeout:1000}, function (err, values)
	{
		if (typeof(values) == "undefined")    {return console.log("values error.");}
		try{
			for(var i=0;i<values[0].length; i++)
			{
				if(Data[i]["IndexValue"].split("-")[1] == "Bool" &&
				   IsDioConditionsTrigger(Data[i], parseInt(values[0][i])) == true)
				{
					var SendString=Data[i]["DefineMessage"]+":"+parseFloat(values[0][i]);
					SendMessage(Data[i]["EventName"], Data[i]["Key"], SendString);
				}
				else if((Data[i]["IndexValue"].split("/")[2].split("-")[0] == "AI" ||
						Data[i]["IndexValue"].split("/")[2].split("-")[0] == "AO") &&
						IsAioConditionsTrigger(Data[i], parseFloat(values[0][i])) == true)
				{
					var SendString=Data[i]["DefineMessage"]+":"+parseFloat(values[0][i]);
					SendMessage(Data[i]["EventName"], Data[i]["Key"], SendString);
				}
			}
		}catch(err){}
	});
}
//OK
function GetDioCurrentVariableValue(BusInterface, Data)
{
	if(typeof(BusInterface) == "undefined")
	{
		return 0;
	}
	BusInterface.ReadVariantArray([Data["RuntimeVariableName"]], {timeout:1000}, function (err, values)
	{
		if (err)	{return console.log(err);}

		Data["UpperLimitValue"]=parseInt(values[0]);
		Data["LowerLimitValue"]=parseInt(values[0]);
		//Global_Index++;
	});
}
//OK
function GetAioCurrentVariableValue(BusInterface, Data, Deadband)
{
	if(typeof(BusInterface) == "undefined")
	{
		return 0;
	}
	BusInterface.ReadVariantArray([Data["RuntimeVariableName"]], {timeout:1000}, function (err, values)
	{
		if (err)	{return console.log(err);}

		Data["UpperLimitValue"]=parseFloat(values[0]) + Deadband;
		Data["LowerLimitValue"]=parseFloat(values[0]) - Deadband;
		//Global_Index++;
	});
}
//OK
function GetDeadband(IndexValue, Condition)
{
	var Return="";
	if(!(IndexValue.split("-")[1]== "Bool"))
	{
		Return=parseFloat(Condition.replace("Deadband=",""));
	}
	return Return;
}
//OK
function GetSwitchValue(IndexValue)
{
	return true;
}

function GetModuleName(ModuleJson, ModuleIndex)
{
	var Return;
	var DeviceName=Object.keys(ModuleJson);
	for(var i=0; i<DeviceName.length; i++)
	{
		if(typeof(ModuleJson[DeviceName[i]][ModuleIndex]) == "undefined" ||
		   typeof(ModuleJson[DeviceName[i]][ModuleIndex]["ModuleName"]) == "undefined")
		{
			continue;
		}
		Return=ModuleJson[DeviceName[i]][ModuleIndex]["ModuleName"];
	}
	return Return;
}

function GetVariableName(VariableJson, ModuleIndex, VariableIndex)
{
	var Return = VariableJson[ModuleIndex][VariableIndex]["VariableName"];
	return Return;
}

function GetRuntimeVariableName(IndexValue)
{
	var Return, ModuleFilePath, VariableFilePath;
	var ModuleType =IndexValue.toString().split("/")[0];
	if(ModuleType == "MRTU"){
		ModuleFilePath  ="/app/Web/public/File/RTU_Module/Module.json";
		VariableFilePath="/app/Web/public/File/RTU_Module/RtuVariable.json";
	}
	else if(ModuleType == "MTCP"){
		ModuleFilePath  ="/app/Web/public/File/TCP_Module/Module.json";
		VariableFilePath="/app/Web/public/File/TCP_Module/TcpVariable.json";
	}
	else if(ModuleType == "MASCII"){
		ModuleFilePath  ="/app/Web/public/File/ASCII_Module/Module.json";
		VariableFilePath="/app/Web/public/File/ASCII_Module/AsciiVariable.json";
	}
	var ModuleJson=JSON.parse(fs.readFileSync(ModuleFilePath, 'utf-8'));
	var VariableJson=JSON.parse(fs.readFileSync(VariableFilePath, 'utf-8'));
	var ModuleIndex=IndexValue.toString().split("/")[1];
	var VariableIndex=IndexValue.toString().split("/")[2];
	var IO=VariableIndex.split("-")[0];
	var ModuleName=GetModuleName(ModuleJson, ModuleIndex);
	var VariableName=GetVariableName(VariableJson, ModuleIndex, VariableIndex);
	Return = ModuleType+"_No."+ModuleIndex+"_"+ModuleName+"_"+IO+"."+VariableName;
	return Return;
}
//OK
function GetSingleVariableDataArray(Index, Setting, Variable)
{
	var IndexValue=Variable[Index]["IndexValue"];
	for(var j=0; j<IndexValue.length; j++)
	{
		var object=new Object();
		object["EventName"]          =Setting[Index]["EventName"];
		object["Key"]                =Setting[Index]["Key"];
		object["IndexValue"]         =Variable[Index]["IndexValue"][j];
		object["RuntimeVariableName"]=GetRuntimeVariableName(Variable[Index]["IndexValue"][j]);
		object["Condition"]          =Variable[Index]["Condition"][j];
		object["Deadband"]           =GetDeadband(IndexValue[j], object["Condition"]);
		object["DefineMessage"]      =Variable[Index]["DefineMessage"][j];
		object["UpperLimitValue"]    ="";
		object["LowerLimitValue"]    ="";
		object["SwitchValue"]        =GetSwitchValue(IndexValue[j]);
		Global_SingleVariableArray.push(object);
		Global_RuntimeVariableArray.push(object["RuntimeVariableName"]);
		if(object["IndexValue"].split("-")[1] == "Bool")
		{
			GetDioCurrentVariableValue(BusObject["BusInterface"], object);
		}
		else
		{
			GetAioCurrentVariableValue(BusObject["BusInterface"], object, object["Deadband"]);
		}
	}
}
//OK
function Initialization(object)
{
	var SetInterval = setInterval(function ()
	{
		if(typeof(BusObject["BusInterface"]) == "undefined")    {return 0;}
		try{
			var Path="/app/Web/public/File/IFTTT_Notify/";
			var Setting=JSON.parse(fs.readFileSync(Path+"Setting.json", 'utf-8'));
			var Variable=JSON.parse(fs.readFileSync(Path+"Variable.json", 'utf-8'));
			var Index=Object.keys(Setting);
			for(var i=0; i<Index.length; i++)
			{
				var Enable   =Setting[Index[i]]["Enable"];
				var EventName=Setting[Index[i]]["EventName"];
				var Key      =Setting[Index[i]]["Key"];
				var Length   =Variable[Index[i]]["IndexValue"].length;
				if(!(Enable==true && Length>0 && EventName!="" && Key!=""))    {continue;}
				
				GetSingleVariableDataArray(Index[i], Setting, Variable);
			}
		}
		catch(err){}
		clearInterval(SetInterval);
	}, 1000);
}

function SurveillanceFile()
{
	var FileSetInterval = setInterval(function ()
	{
		var SettingTime=fs.statSync("/app/Web/public/File/IFTTT_Notify/Setting.json");
		var VariableTime=fs.statSync("/app/Web/public/File/IFTTT_Notify/Variable.json");
		if(SettingTime["mtimeMs"] != SettingFileTime["mtimeMs"] && VariableTime["mtimeMs"] != VariableFileTime["mtimeMs"])
		{
			 SettingFileTime["mtimeMs"] = SettingTime["mtimeMs"];
			 VariableFileTime["mtimeMs"] = VariableTime["mtimeMs"];
			 //Global_Index = 0;
			 Global_RuntimeVariableArray=new Array();
			 Global_SingleVariableArray=new Array();
			 Initialization();
		}
	}, 1000);
}

function MainFunction()
{
	var SetInterval = setInterval(function ()
	{
		if(Global_SingleVariableArray.length == 0)
		{
			return 0;
		}
/*
		else if(Global_SingleVariableArray.length == Global_Index)
		{
			LoopJudgment(BusObject["BusInterface"], Global_RuntimeVariableArray, Global_SingleVariableArray);
		}
*/
		LoopJudgment(BusObject["BusInterface"], Global_RuntimeVariableArray, Global_SingleVariableArray);
	}, 1000);
}

function GetDbusInterface(Bus, BusObject)
{
	var SetInterval = setInterval(function()
	{
		Bus.getInterface('UA_runtime.RW.Variable',
						 '/UA_runtime/RW/Variable',
						 'UA_runtime.RW.Variable',function(err, iface)
						{
							if(!err)
							{
								BusObject["BusInterface"]=iface;
								clearInterval(SetInterval);
							}
						});
	}, 1000);
}




//----------Main----------

var BusObject=new Object();
BusObject["BusInterface"]=undefined;
GetDbusInterface(Bus, BusObject);

var Global_Index=0;
var Global_RuntimeVariableArray=new Array();
var Global_SingleVariableArray=new Array();
Initialization();

var SettingFileTime=fs.statSync("/app/Web/public/File/IFTTT_Notify/Setting.json");
var VariableFileTime=fs.statSync("/app/Web/public/File/IFTTT_Notify/Variable.json");

MainFunction();
SurveillanceFile();