/**
 * 
 */
var forkCP = function(contractName,nodeID,contractPort) {
	
	var request = {};
	request.action = "downloadContract";
	
	
	//发送请求查找该contractName对应的projectName，并通过nodeID获得对应的node的url
	$.ajax(
			{
				url : "./NodeCenter?action=find&contractName="
						+ contractName + "&nodeID=" + nodeID,
				dataType : "json"
			}).done(function(result) {
		// console.log(result);
		var res = result.data.split("/");
		var res2 = res[res.length-1].split("\"");
		request.mainHost = res[2];
		request.projectName = res2[res2.length-2];
		globalProjectName = res2[res2.length-2];	
		request.fileName = request.projectName + "_" + new Date().getTime()
		+ ".ypk";
		
		
		
		//存储该时刻合约执行的状态信息
		dumpContract(contractName,res[2],contractPort);
		
	
		var host = $("#host").val();
		disposeContract(request, host);
	});		
}


var dumpContract = function(contractName,nodeUrl,contractPort) {
	
	$.ajax(
			{
				url : "./NodeCenter?action=DumpMemory&nodeUrl="
						+ nodeUrl + "&contractPort=" + contractPort
						+ "&contractName=" + contractName,
				dataType : "json"
			}).done(function(result) {
		// console.log(result);
		var content = result.data;
		
		//调用目标节点的ContractController中方法将字符串类型的合约状态存储为dyjs文件
		var host = $("#host").val();
		var url = getControlWsUrl(host);
		//console.log("[nodeCenter.js] host = " + host + " ; url = " + url);
		wssocket = new WebSocket(url);
		var saveFile = {};
		saveFile.action = "writeDyjs";
		saveFile.content = content;
		saveFile.target = "/memoryDumps/" + contractName + "_"
				+ new Date().getTime() + ".dyjs";
		saveFile.contractID = contractName;
		wssocket.onopen = function() {
			//console.log("[nodeCenter.js]与目标节点连接成功");
			wssocket.send(JSON.stringify(saveFile));
		}
		
		
	});
	
};

var disposeContract = function(request, host) {
	// console.log("[nodeCenter.js] disposeContract:" + host + "-->"
	// 		+ JSON.stringify(request));
	var wsUrl = getFileWsUrl(host);
	var fileWs = new WebSocket(wsUrl);
	fileWs.onerror = function(error) {
		console.log(error);
	};
	fileWs.onopen = function(error) {
		fileWs.send(JSON.stringify(request));
	};
	fileWs.currHost = host;
	fileWs.zipInfo = request;
	fileWs.onmessage = downloadHandler;
}



var downloadHandler = function(obj, wssocket) {
	console.log("[nodeCenter.js] downloadHandler : ");
	var currHost = $("#host").val();
	// console.log(event);
	data = event.data;
	// console.log("   -->" + data);
	try {
		var obj = JSON.parse(data);
		switch (obj.action) {
		case "onDownloadContract":
			// console.log(JSON.stringify(obj));
			//console.log("[nodeCenter.js] downloadHandler 执行时间 " + obj.executeTime);
			progressbarUpdate(obj.executeTime);
			//updateProgress(this.contractIndex, this.currHost,obj.executeTime * 0.95);
			if (obj.data == "success") {
				//console.log("[nodeCenter.js] downloadHandler successs");
				//console.log("[nodeCenter.js] downloadHander host = " + currHost + " ; globalProjectName = " + globalProjectName);
				startContractWithHost(currHost, globalProjectName);
				this.close();
			}
			break;
		case "onStartContract":
			//updateProgress(wssocket.contractIndex, wssocket.currHost, 100);
			wssocket.close();
			break;
		default:
		}
	} catch (err) {
		console.log(err);
	}
}


var progressbarUpdate = function(time){
	//console.log("[nodeCenter.js] progressbarUpdate time = " + time);
	$("#progressbar").val(time);
}

var startContractWithHost = function(host, fileName) {
	
	var wsUrl = getControlWsUrl(host);
	//console.log("[nodeCenter.js] wsUrl = " + wsUrl);
	var controller = createWssocket(wsUrl, function() {
		// onopen;
		var request = {};
		request.action = "startContractInTempZips";
		request.owner = global.privKey;
		request.path = fileName;
		request.script = "empty";
		controller.send(JSON.stringify(request));
		//console.log("[nodeCenter.js] request.owner = " + request.owner + " ; request.path = " + request.path);
		//this.contractIndex = contractIndex;
		//this.currHost = host;
	}, downloadHandler);
	console.log("[nodeCenter.js] 结束");
};


var initGlobal = function() {
	window.global = {};
	globalProjectName = "";
	global.privKey = localStorage.getItem("PrivKey");
	if (global.privKey == undefined || global.privKey == null
			|| global.privKey.length < 100) {
		generate();
	}
}

var init = function() {
	initGlobal();
};

var generate = function() {
	$.ajax({
		url : "./SCManager?action=generatePrivateKey",
		dataType : "json"
	}).done(function(result) {
		if (result.status) {
			localStorage.setItem("PrivKey", result.data);
			alert("Key successfully generated!");
			initRest();
		}
	});
}


var getControlWsUrl = function(host) {
	var prefix = "ws://";
	if (document.location.href.startsWith("https"))
		prefix = "wss://";
	var path = document.location.pathname.lastIndexOf("/");
	path = document.location.pathname.substr(0, path + 1);
	path += "SCExecutor";
	return prefix + host + path;
};