var PipesClass = new require('./internal/pipes.js');
var Pipes = new PipesClass

var CheckProcessClass = new require('./internal/checkprocess.js');
var CheckProcess = new CheckProcessClass

var CustomClass = new require('./internal/custom.js');
var Custom = new CustomClass

Custom.Init()

CheckProcess.Start(process.argv[2])

var ApiCallbacks = {}
var ApiData = {}


Pipes.Start(process.argv[2], function(Data){
	
	//Parse incoming messages
	var Obj = null
	try
	{
		Obj = JSON.parse(Data)
	}catch(e)
	{
		Obj = null
	}
	
	if(!Obj)
		return

	//Run new function
	if(Obj["t"] == 0)
	{
		var FunctionName = Obj["f"]

		if(!Custom.FunctionExists(FunctionName))
		{
			Obj["e"] = "Function " + FunctionName + " not exists"
			Obj["s"] = false
			Custom.ClearTestData(Obj)
			Pipes.Write(JSON.stringify(Obj));
			return
		}

		var Variables = Obj["v"]

		var Callback = function()
		{
			Obj["e"] = ""
			Obj["s"] = true
			Custom.ClearTestData(Obj)

			Pipes.Write(JSON.stringify(Obj));		
			
		}
		
		var CallbackFail = function(error)
		{
			Obj["e"] = error
			Obj["s"] = false
			Custom.ClearTestData(Obj)
			Pipes.Write(JSON.stringify(Obj));		
		}

		var Api = function(api, callback)
		{
			Obj["a"] = api
			ApiCallbacks[Obj["id"]] = callback
			Custom.ClearTestData(Obj)
			Pipes.Write(JSON.stringify(Obj));		
		}

		var ConsoleLog = function(log)
		{
			try{
				var Send = {}
				if(typeof(log) == "object")
					Send["l"] = JSON.stringify(log)
				else
					Send["l"] = log.toString()
				Send["id"] = Obj["id"]
				Pipes.Write(JSON.stringify(Send));			
			}catch(e)
			{
				try{
					var Send = {}
					Send["l"] = "undefined"
					Send["id"] = Obj["id"]
					Pipes.Write(JSON.stringify(Send));			
				}catch(e)
				{

				}
			}
			
		}

		Custom.Call(FunctionName, Variables, Callback, CallbackFail, Api, Obj["id"], ApiData, ConsoleLog)	
	}

	//Return api
	if(Obj["t"] == 1)
	{
		if(!(Obj["id"] in ApiCallbacks))
		{
			Obj["e"] = "Task id not found"
			Obj["s"] = false
			Custom.ClearTestData(Obj)	
			Pipes.Write(JSON.stringify(Obj));
			return	
		}
		var Callback = ApiCallbacks[Obj["id"]]
		delete ApiCallbacks[Obj["id"]]
		Callback(Obj["v"], false)
	}

	//Kill task
	if(Obj["t"] == 2)
	{
		if(Obj["id"] in ApiCallbacks)
		{
			var Callback = ApiCallbacks[Obj["id"]]
			delete ApiCallbacks[Obj["id"]]
			Callback(Obj["v"], true)
		}
		if(Obj["id"] in ApiData)
		{
			var Data = ApiData[Obj["id"]]
			Data["-BAS-NEED-STOP-"]=true
		}
		
	}

	//Stats
	if(Obj["t"] == 3)
	{
		var res = {}
		res["s1"] = Object.keys(ApiData).length
		res["s2"] = Object.keys(ApiCallbacks).length
		Pipes.Write(JSON.stringify(res));
	}
})