var applyRole = function(role) {
	global.wssocket.send("{\"action\":\"applyNodeRole\",\"role\":\"" + role
			+ "\",\"pubKey\":\"" + global.sm2Key.publicKey + "\"}");
};
var WSHandler = function(event) {
	data = event.data;
	try {
		var obj = JSON.parse(data);
		switch (obj.action) {
		case 'onTransferTo':
			onTransferTo(obj);
			break;
		case 'onListMemoryFiles':
			onListMemoryFiles(obj);
			break;
		case 'onDumpContract':
			onDumpContract(obj);
			break;
		case 'onChangeDumpPeriod':
			onChangeDumpPeriod(obj);
			break;
		case 'onGetDumpPeriod':
			onGetDumpPeriod(obj);
			break;
		case 'onStaticVerifyResult':
			onStaticVerifyResult(obj);
			break;
		case "onListContractProcess":
			onListContractProcess(obj);
			break;
		case "onDeleteFile":
			onDeleteFile(obj);
			break;
		case "onCancelAuth":
			onCancelAuth(obj);
			break;
		case "onDownloadContract":
			onDownloadFile(obj);
			break;
		case "onChangePublic":
			onChangePublic(obj);
			break;
		case "onListProjects":
			onListProjects(obj);
			break;
		case "onListProject":
			onListProject(obj);
			break;
		case "onListLocalNodeLog":
			onListLocalNodeLog(obj);
			break;
		case "onListLocalNodeLogPie":
			onListLocalNodeLogPie(obj);
			break;
		case "onListLocalNodeLogLine":
			onListLocalNodeLogLine(obj);
			break;
		case "onListLocalContractLog":
			onListLocalContractLog(obj);
			break;
		case "onListLocalContractLogPie":
			onListLocalContractLogPie(obj);
			break;
		case "onListLocalContractLogLine":
			onListLocalContractLogLine(obj);
			break;
		case "onGetNodeSessionID":
			onGetNodeSessionID(obj);
			break;
		case "onLogin":
			onNodeLogin(obj);
			break;
		case "onGetNodeRole":
			onGetNodeRole(obj);
			break;
		case "onApplyRole":
			onApplyRole(obj);
			break;
		case "onListAllAuthRole":
			onListAllAuthRole(obj);
			break;
		case "onListUnAuthRole":
			onListUnAuthRole(obj);
			break;
		case "onDeleteRole":
			onDeleteRole(obj);
			break;
		case "onCountRole":
			onCountRole(obj);
			break;
		case "onAuthNodeRole":
			onAuthNodeRole(obj);
			break;
		case "onApplyNet":
			onApplyNet(obj);
			break;
		case "onLoadNodeConfig":
			onLoadNodeConfig(obj);
			break;
		case "onChangeNodeName":
			onChangeNodeName(obj);
			break;
		case "onChangeYJSPath":
			onChangeYJSPath(obj);
			break;
		case "onGetLicenceExpiredDate":
			$("#expiredDate").html(convertDate(data.data));
			break;
		case "onGetPeerID":
			global.peerID = obj.data;
			// getNodeTrustUnits();//still connecting to centerportalws
			break;
		case "onViewContractInstance":
			onViewContractInstance(obj);
			break;
		case 'onExecuteResult':
			onExecuteResult(obj);
			break;
		case 'onUploadFile':
			onUploadFile(obj);
			break;
		case 'onStartContract':
			onStartContract(obj);
			break;
		case 'onKillContractProcess':
			onStopContract(obj);
			break;
		case 'onKillAllContract':
			onKillAllContract(obj);
			break;
		case 'onSetPermission':
			onSetPermission(obj);
			break;
		case 'onOutputStream':
			displayOutput(obj);
			break;
		case 'onOutputStream':
			displayOutput(obj);
			break;
		case 'onChangeNodeCenter':
			onChangeNodeCenter(obj);
			break;
		case 'onHashResult':
			onHashResult(obj);
			break;
		default:
			displayOutput(obj);
			break;
		}
	} catch (err) {
		console.log(err);
	}
};

var displayOutput = function(obj) {
	console.log(obj);
};

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);
	if (path.indexOf("SCIDE") < 0)
		path += "SCIDE/";
	path += "SCExecutor";
	return prefix + host + path;
};
var initWSocket = function() {
	var host = document.location.host;
	var url = getControlWsUrl(host);
	console.log("connect ws:" + url);
	global.wssocket = createWssocket(url, function() {
		getSession();
		loadNodeConfig();// get center portal & create centerportalsocket in
							// onLoadNodeConfig
	}, WSHandler);

};

var centerportalWSHandler = function(event) {
	data = event.data;
	try {
		var obj = JSON.parse(data);
		switch (obj.action) {
		case "onGetNodeTrustUnits":
			onGetNodeTrustUnits(obj);
			break;
		case 'onSessionID':
			onSessionID(obj);
			break;
		case 'onStartContract':
			onStartContract(obj);
			break;
		case 'onStartTrustfulContract':
			onStartTrustfulContract(obj);
			break;
		case 'onDistributeContract':
			onDistributeContract(obj);
			break;
		case 'onDistributeFinish':
			onDistributeFinish(obj);
			break;
		default:
			break;
		}
	} catch (err) {
		console.log(err);
	}
};

var getSession = function() {
	global.wssocket.send("{\"action\":\"getNodeSessionID\"}");
};
var exportSMKeyPair = function() {
	$("#dialog").html("Save Your key:<br/>" + JSON.stringify(global.sm2Key))
	$("#dialog").dialog("open");
};
// ====== wsHandler
var onGetNodeSessionID = function(data) {
	console.log("onGetNodeSessionID");
	global.session = data.session;
	var loginParam = {};
	loginParam.pubKey = global.sm2Key.publicKey;
	loginParam.signature = sm2.doSignature(global.session,
			global.sm2Key.privateKey);
	loginParam.action = "login";
	global.wssocket.send(JSON.stringify(loginParam));
};
var onNodeLogin = function(data) {
	console.log("onNodeLogin");
	var param = {};
	param.action = "getNodeRole";
	global.wssocket.send(JSON.stringify(param));
};
var onGetNodeRole = function(data) {
	console.log("onGetNodeRole");
	pubkeyDialogVue.myRole = data.data;
	global.myRole = data.data;
	loadUserMan();

};
var onListLocalNodeLog = function(data) {
	var userManTab = $("#v-pills-userManager-tab")[0];
	var isActive = (userManTab.getAttribute("aria-selected") == "true");
	if (isActive) {
		drawUserActivityGraph(data);
	} else {
		drawLocalLogGraphs(data);
	}
};
var onListAllAuthRole = function(data) {
	console.log("onListAllAuthRole");
	fillAuthRoleData(data.data);
};

var onListUnAuthRole = function(data) {
	console.log("onListUnAuthRole");
	fillUnAuthRoleData(data.data);
};

var onApplyNet = function(data) {
	console.log("onApplyNet");
};
var onCountRole = function(data) {
	console.log("onCountRole");
	setUserTypeDistribution(data.data);
}

var onAuthNodeRole = function(data) {
	myToast("授权/忽略操作", data.data);
	if (data.data == "success") {
		var arg = {};
		arg.action = "listAllAuthRole";
		global.wssocket.send(JSON.stringify(arg));
		var arg = {};
		arg.action = "listUnAuthRole";
		global.wssocket.send(JSON.stringify(arg));
	}
};

var onApplyRole = function(data) {
	myToast("申请操作", data.data);
};
var onDeleteRole = function(data) {
	myToast("删除操作", data.data);
	var loginAllUser = {};
	loginAllUser.action = "listAllAuthRole";
	global.wssocket.send(JSON.stringify(loginAllUser));
};

// ====== wsHandler done!
var myToast = function(title, msg) {
	toastVue.toastTitle = title;
	toastVue.toastMessage = msg;
	$("#alertDiv").toast("show");

}

var countChar = function(str, c) {
	var ret = 0;
	for (var i = 0; i < str.length; i++) {
		if (str.charAt(i) == c)
			ret++;
	}
	return ret;
}
var generate = function() {
	var key = sm2.generateKeyPairHex();
	global.sm2Key = key;
	localStorage.setItem("PrivKey", JSON.stringify(key));
}

var killAllContract = function() {
	var request = {};
	request.action = "killAllContract";
	global.wssocket.send(JSON.stringify(request));
};

var init = function() {
	initVue();
	initGlobal();
	initWSocket();
};
var getRequestParameters = function() {
	var arr = (location.search || "").replace(/^\?/, '').split("&");
	var params = {};
	for (var i = 0; i < arr.length; i++) {
		var data = arr[i].split("=");
		if (data.length == 2) {
			params[data[0]] = data[1];
		}
	}
	return params;
};
var prefix = "./SCIDE/SCManager?";
if (document.location.href.indexOf("SCIDE") != -1) {
	prefix = "./SCManager?";
}
$.ajax({
	url : prefix + "action=listAdapters",
	dataType : "json"
}).done(function(result) {
	console.log("receive result");
}).error(function(result) {
	console.log("receive result err");
	console.log(result);
});
