var createWssocket = function(wsurl, onopen, handler) {
	var retsocket = {};
	var wssocket = new WebSocket(wsurl);
	wssocket.onerror = function(error) {
		console.log(error);
	};
	wssocket.onopen = onopen;
	wssocket.onclose = function(error) {
	};
	retsocket.receiveSeg = function(obj) {
		if (obj.cid == 'start') {
			retsocket.toReceive = "";
		}
		retsocket.toReceive += obj.data;
		if (obj.cid == 'done') {
			// console.log("[receiveSeg] Received AllData:" + retsocket.toReceive);
			var event = {};
			event.data = retsocket.toReceive;
			retsocket.toReceive = "";
			handler(event);
		}
	};
	wssocket.onopen = function(error) {
		var pingObj = {};
		pingObj.action = "ping";
		wssocket.send(JSON.stringify(pingObj));
		listContractProcess();
	};
	wssocket.onmessage = function(event) {
		var obj = JSON.parse(event.data);
		switch (obj.action) {
		case 'sendNextSegment':
			retsocket.sendNextSegment();
			break;
		case 'sendSeg':
			retsocket.receiveSeg(obj);
			break;
		default:
			handler(event);
		}
	};

	retsocket.isSending = false;
	retsocket.sendList = [];
	retsocket.monitor = function() {
		if (!retsocket.isSending) {
			if (retsocket.sendList.length > 0) {
				retsocket.send(retsocket.sendList.pop());
			}
		}
		setTimeout(retsocket.monitor, 1000);
	};
	// TODO: we don't need monitor at all?
	retsocket.monitor();
	retsocket.send = function(str) {
		if (str.length > 1024) {
			if (retsocket.isSending) {
				retsocket.sendList.push(str);
				return;
			}
			retsocket.isSending = true;
			retsocket.toSend = str.substr(1024);
			var obj = {};
			obj.isSegment = true;
			obj.data = str.substr(0, 1024);
			wssocket.send(JSON.stringify(obj));
		} else
			wssocket.send(str);
	};
	retsocket.sendNextSegment = function() {
		var str = retsocket.toSend;
		if (str.length > 1024) {
			retsocket.toSend = str.substr(1024);
			var obj = {};
			obj.isSegment = true;
			obj.data = str.substr(0, 1024);
			wssocket.send(JSON.stringify(obj));
		} else {
			retsocket.toSend = "";
			var obj = {};
			obj.isSegment = false;
			obj.data = str;
			wssocket.send(JSON.stringify(obj));
			retsocket.isSending = false;
			if (retsocket.sendList.length > 0) {
				retsocket.send(retsocket.sendList.pop());
			}
		}
	};
	return retsocket;
};

// FirstWay:HttpGet(Automatically allocate privKey at server)
// privKey is not necessary. Privkey can be generated from:
// http://39.106.6.6:8080/SCIDE/setPrivkey.html if needed
// Sample URL:
// http://39.106.6.6:8080/SCIDE/SCManager?action=executeContract&contractID=abc&operation=main&arg=%5B%7B%22score%22%3A20%7D%2C%7B%22score%22%3A20%7D%5D
// Sample CURL Commnad: curl
// 'http://39.106.6.6:8080/SCIDE/SCManager?action=executeContract&contractID=abc&operation=main&arg=%5B%7B%22score%22%3A20%7D%2C%7B%22score%22%3A20%7D%5D'
// -H 'Referer: http://jquery.com/' -H 'User-Agent: Mozilla/5.0 (Macintosh;
// Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko)
// Chrome/72.0.3626.119 Safari/537.36' --compressed

// SecondWay:jquery.ajax, jsonp
// use this way to "Cross Domain"
global = {};
privKey = sm2.generateKeyPairHex();

$.ajax({
	url : "http://39.106.6.6:8080/SCIDE/SCManager",
	data : {
		"action" : "executeContract",
		"contractID" : "abc",
		"operation" : "main",
		"arg" : "[{\"score\":20},{\"score\":20}]",
	},
	dataType : "jsonp"
}).done(function(result) {
	global.r = result;
	// console.log(result);
});

$.ajax(
		{
			url : "http://39.106.6.6:8080/SCIDE/SCManager",
			data : {
				"action" : "executeContract",
				"contractID" : "abc",
				"operation" : "main",
				"arg" : "[{\"score\":20},{\"score\":20}]",
				"requester" : privKey.publicKey,
				"signature" : sm2.doSignature(
						"abc|main|[{\"score\":20},{\"score\":20}]|"
								+ privKey.publicKey, privKey.privateKey)
			},
			dataType : "jsonp"
		}).done(function(result) {
	global.r = result;
	// console.log(result);
});
// ThirdWay:websocket
// Leverage "createWssocket"
var url = "ws://39.106.6.6:8080/SCIDE/SCExecutor";
global = {};
WSHandler = function(a) {
	console.log("ReceiveMsg:");
	global.a = a;
	// console.log(a);
}
wssocket = createWssocket(url, WSHandler);
var content = {};
privKey = sm2.generateKeyPairHex();
content.action = "main";
content.arg = "[{\"score\":20},{\"score\":20}]";
var request = {};
request.action = "executeContract";
request.contractID = "abc";
request.arg = JSON.stringify(content);
request.pubkey = privKey.publicKey;
// contractID + "|" + action + "|" + arg + "|" + requester;
request.signature = sm2.doSignature(request.contractID + "|" + content.action
		+ "|" + content.arg + "|" + privKey.publicKey, privKey.privateKey);

// Wait until connected

wssocket.send(JSON.stringify(request));

// SendMock
// Sample URL:
// http://localhost:8080/SCIDE/SCManager?action=sendMockTransaction&count=1000

