/*
 * Global.contractID
 * Global.memoryFiles
 * Global.currentFile
 * Global.currentNode
 * Global.nodes
 */

var initContracts = function(){
	$.ajax({
		url : "./CMManager?action=listContractProcess",
		dataType : "json"
	}).done(function(result) {
		// console.log(result);
		Global.result = result;
		listNodes();
		updateTabs(JSON.parse(result.data));
	});
}

var updateTabs = function(data) {
	for (var i = 0; i < data.length; i++) {
		var obj = data[i];
		$("#contracts").editableSelect('add', obj.name);
	}
	if (data.length > 0)
		$("#contracts").editableSelect()[0].value = data[0].name;
	Global.contractID = $("#contracts")[0].value;
	updateContract();
	clickContract();
};

var clickContract = function() {
	var contractID = $("#contracts")[0].value;
	if (contractID != Global.contractID) {
		Global.contractID = contractID;
		updateContract();
	}
}

var switchMemoryFile = function(i) {
	Global.currentFile = Global.memoryFiles[i];  //设置当前选中的文件，currentFile为文件名
	$("#notice").html("Choose time " + Global.currentFile + " to travel.");
	
	for(var j = 0;j < Global.memoryFiles.length;j++){
		if(j == i){
			document.getElementById("memoryFile" + j).style.color="#a9423e";   //改变选中文件颜色
		}
		else{
			document.getElementById("memoryFile" + j).style.color="black";
		}
	}
}

var updateContract = function() {
	var name = Global.contractID;
	$("#show").html("Contract " + name + " has been choosed.");
	listMemoryFiles(); //更新选择的合约需更新memoryFiles
}

var updateMemoryFiles = function(data) {
	Global.memoryFiles = data;  //首次设置当前Global.memoryFiles值
	var html = "<label><b>Time to Choose</b></label>";
	for(var i = 0;i < data.length;i++){
		html += "<h4 onclick=\"switchMemoryFile(" + i + ")\" class='projectButton' id=\"memoryFile" + i + "\">&nbsp;&nbsp;" + data[i] + "</h4>";
	}
	$("#memoryFilesArea").html(html);
	printTimeTravelLog();
}

var listMemoryFiles = function() {
	console.log("listMemoryFiles : ");
	$.ajax({
		url : "./CMManager?action=listMemoryFiles&target=" + Global.contractID,
		dataType : "json"
	}).done(function(result) {
		Global.result = result;
		// console.log("[listMemoryFiles] result.data = " + result.data);
		if(result.data == "" || result.data == null){
			$("#memoryFilesArea").html("<label><b>Time to Choose</b></label></br><h4>This contract has no memory files,can't travel!</h4>");
		}else if(result.data == "all"){
			$("#memoryFilesArea").html("<label><b>Time to Choose</b></label></br><h4>Please choose a contract first!</h4>");
		}else{
			updateMemoryFiles(JSON.parse(result.data));
		}
	});
	
}

var dumpContract = function() {
	$.ajax({
		url : "./CMManager?action=dumpContract&contractID=" + Global.contractID + "&target=" + Global.contractID,
		dataType : "json"
	}).done(function(result) {
		// console.log("dumpContract result : " + result);
		Global.result = result;
		if(result.data == "success"){
			$("#notice").html("Contract " + Global.contractID + " has been dumped successfully.Meomry file size is " + result.size + " . Dump time is " + result.time + ".");
			printTimeTravelLog();
			listMemoryFiles();  //产生新的memory文件，需要刷新
		}
		else{
			$("#notice").html("Contract " + Global.contractID + " dumped failed!");
			printTimeTravelLog();
		}	
	});
}

var backtoContract = function() {
	// console.log("Global.currentFile=" + Global.currentFile);
	if(Global.currentFile == null){
		alert("Please choose time to travel!");
		$("#notice").html("Please choose time to travel!");
		return;
	}
	$.ajax({
		url : "./CMManager?action=loadMemory&contractID=" + Global.contractID + "&target=" + Global.currentFile + "&direction=back",
		dataType : "json"
	}).done(function(result) {
		Global.result = result;
		if(result.data == "success"){
			$("#notice").html("Contract " + Global.contractID + " has travelled back to past successfully.Meomry file size is " + result.size + " . Travel time is " + result.time + ".");
			printTimeTravelLog();
		}
		else{
			alert(result.data);
			$("#notice").html(result.data);
			printTimeTravelLog();
		}	
	});
}

var gotoContract = function() {
	// ("Global.currentFile=" + Global.currentFile);
	if(Global.currentFile == null){
		alert("Please choose time to travel!");
		$("#notice").html("Please choose time to travel!");
		return;
	}
	$.ajax({
		url : "./CMManager?action=loadMemory&contractID=" + Global.contractID + "&target=" + Global.currentFile + "&direction=go",
		dataType : "json"
	}).done(function(result) {
		Global.result = result;
		if(result.data == "success"){
			$("#notice").html("Contract " + Global.contractID + " has travelled to future successfully. Meomry file size is " + result.size + " . Travel time is " + result.time + ".");
			printTimeTravelLog();
		}
		else{
			alert(result.data);
			$("#notice").html(result.data);
			printTimeTravelLog();
		}	
	});
}

var printTimeTravelLog = function() {
	$.ajax({
		url : "./CMManager?action=printTimeTravelLog",
		dataType : "json"
	}).done(function(result) {
		Global.result = result;
		$("#log").html(result.data);		
	});
}

var printTransferLog = function() {
	$.ajax({
		url : "./CMManager?action=printTransferLog",
		dataType : "json"
	}).done(function(result) {
		Global.result = result;
		$("#log2").html(result.data);		
	});
}

var listNodes = function() {
	console.log("listNodes : ");
	$.ajax({
		url : "./CMManager?action=listForkNodes",
		dataType : "json"
	}).done(function(result) {
		Global.result = result;
		console.log("[listNodes] result.data = " + result.data);
		if(result.data == "" || result.data == null){
			$("#nodesArea").html("<label><b>No node to choose!!!</b></label></br>");
		}else{
			updateNodes(JSON.parse(result.data));
		}
		
		printTransferLog();
	});
}

var updateNodes = function(data) {
	console.log("updateNodes : " + data);
	Global.nodes = data;  
	var html = "<label><b>Nodes to Choose</b></label>";
	for(var i = 0;i < data.length;i++){
		html += "<h4 onclick=\"switchNode(" + i + ")\" class='projectButton' id=\"node" + i + "\">&nbsp;&nbsp;" + "[node] " + data[i] + "</h4>";
	}
	$("#nodesArea").html(html);
	printTransferLog();
}

var switchNode = function(i) {
	Global.currentNode = Global.nodes[i];  
	$("#notice2").html("Choose node " + Global.currentNode + " to transfer.");
	
	for(var j = 0;j < Global.nodes.length;j++){
		if(j == i){
			document.getElementById("node" + j).style.color="#a9423e";  
		}
		else{
			document.getElementById("node" + j).style.color="black";
		}
	}
}

var transfer = function(i) {
	console.log("Global.currentNode=" + Global.currentNode);
	if(Global.currentNode == null){
		alert("Please choose node to transfer!");
		$("#notice2").html("Please choose a node to transfer!");
		return;
	}
	
	//先将合约代码传过去并在选中的节点上启动
	
	
	
	
	
	
	
	
	var mode;
	switch(i){
		case 0 :
			mode = "memoryTransfer";
			//memory dump，fork
			
			
			break;
		case 1 :
			mode = "traceTransfer";
			break;
		case 2 :
			mode = "simpleTransfer";
			break;
		case 3 :
			mode = "fastTransfer";
			break;
		default:
			;
	}
	$("#notice2").html("Use mode " + mode +  " to transfer!");
	
	
	/*
	var urlstr = "http://" + Global.currentNode + ":8080/SCIDE/CMManager?action=forkContract&contractID=" + Global.contractID + "&method="
	$.ajax({
		url : urlstr,
		dataType : "json"
	}).done(function(result) {
		Global.result = result;
		
		if(result.data == "success"){
			console.log("[transfer] test success!");
			$("#notice2").html("Contract " + Global.contractID + " has transferred successfully.");
			printTransferLog();
		}
		else{
			alert("Transfer error : " + result.data);
			$("#notice2").html(result.data);
			printTransferLog();
		}	
		
		
		//从这继续写
		printTransferLog();
	});
	*/
	
	
	
	/*
	var host = Global.currentNode;
	if(host == "127.0.0.1"){
		host += ":18000"
	}else{
		host += ":8080"
	}
	var wsUrl = getControlWsUrl(host);
	console.log("[transfer] wsUrl=" + wsUrl);
	
	var sock = new WebSocket(wsUrl);
	
	var controller = createWssocket(wsUrl, function() {
		// onopen;
		var request = {};
		request.action = "forkContract";
		request.script = "empty";
		controller.send(JSON.stringify(request));
	}, transferHandler);
	*/
}

var transferHandler = function(obj){
	console.log("[transferHandler]");
	printTransferLog();
	console.log(obj);
	var obj2 = JSON.parse(obj.data );
	console.log(obj2.data);
}