import WebSocket from 'ws';

export default class Msg {
	private static  sendBufLen = 0;
	private static sendBuf = new ArrayBuffer(512);
	private static sendBufDV = new DataView(Msg.sendBuf, 0);
	static websocket;
	static isConnect: Boolean;
	static isConnecting: boolean;
	static websocketM;
	static isConnectM:Boolean;
	static isConnectingM:Boolean;
	static isInitiative: boolean = false;
	static handler;
	static account;

	static connect(url, inputAccount) {
		console.log("开始连接 url ============== ", url);
		if (Msg.isConnect) {
			console.log("msg connect 连接已存在");
		} else if (Msg.isConnecting) {
			console.log("msg connect 正在连接中");
		} else {
			Msg.isConnect = false;
			Msg.isConnecting = true;
            Msg.websocket = new WebSocket(url);
			Msg.websocket.binaryType = "arraybuffer";
			Msg.websocket.onopen = function (evt) { Msg.onOpen(evt) };
			Msg.websocket.onclose = function (evt) { Msg.onClose(evt) };
			Msg.websocket.onmessage = function (evt) { Msg.handler.onMessage(evt) };
			Msg.websocket.onerror = function (evt) { Msg.onError(evt) };
			Msg.account = inputAccount;
		}
	}

	static onOpen(evt) {
		Msg.isConnecting = false;
		if (Msg.websocket.readyState == 1 && !Msg.isConnect) {
			Msg.isConnect = true;
			console.log("连接成功");
		} else {
			console.log("连接服务器失败(" + Msg.websocket.readyState + ")")
		}
	}

	static onClose(evt) {
		Msg.isConnect = false;
		Msg.isConnecting = false;
		if (Msg.websocket) {
			Msg.websocket.close();
		}
		if (Msg.isInitiative) Msg.isInitiative = false;
		if (Msg.isConnectM) Msg.websocketM.close();
	}

	static onError(evt) {
		Msg.isConnect = false;
		Msg.isConnecting = false;
		if (Msg.websocket) {
			Msg.websocket.close();
		}
		if (Msg.isConnectM) Msg.websocketM.close();
		// PlatformManager.onLoginError();
		// LoadingPanel.instance.tip = "连接服务器失败(" + Msg.websocket.readyState + ")";
	}

	static connectM(url)
	{
		if (Msg.isConnectM) {
			console.log("msg connectM 连接已存在");
		} else if (Msg.isConnectingM) {
			console.log("msg connectM 正在连接中");
		} else {
			Msg.isConnectM = false;
			Msg.isConnectingM = true;
			Msg.websocketM = new WebSocket(url);
			Msg.websocketM.binaryType="arraybuffer";
			Msg.websocketM.onopen = function(evt) { Msg.onOpenM(evt) };
			Msg.websocketM.onclose = function(evt) { Msg.onCloseM(evt) };
			Msg.websocketM.onmessage = function(evt) { Msg.handler.onMessageM(evt) };
			Msg.websocketM.onerror = function(evt) { Msg.onErrorM(evt) };
		}
	}

	static onOpenM(evt) {
		Msg.isConnectingM = false;
		if (Msg.websocketM.readyState == 1 && !Msg.isConnectM) {
			Msg.isConnectM = true;
			// Msg.CG_MIDDLE_LOGIN(account);
		} else {
			//trace("sopcket middle err:", websocketM.readyState);
		}
	}

	static onCloseM(evt)
	{
		Msg.isConnectM = false;
		Msg.isConnectingM = false;
		console.log('onCloseM>>>>>>>>>>>>>>>>>>>>>>>>>>')
		if (Msg.websocketM) {
			Msg.websocketM.close();
		}
	}

	static onErrorM(evt)
	{
		Msg.isConnectM = false;

		Msg.isConnectM = false;
		Msg.isConnectingM = false;
		console.log('onErrorM>>>>>>>>>>>>>>>>>>>>>>>>>>')
		if (Msg.websocketM) {
			Msg.websocketM.close();
		}
	}	

	static writeDouble(n) {
		Msg.sendBufDV.setFloat64(Msg.sendBufLen, n);
		Msg.sendBufLen = Msg.sendBufLen + 8;
	}

	static writeInt(n) {
		Msg.sendBufDV.setInt32(Msg.sendBufLen, n);
		Msg.sendBufLen = Msg.sendBufLen + 4;
	}

	static writeUint(n) {
		Msg.sendBufDV.setUint32(Msg.sendBufLen, n);
		Msg.sendBufLen = Msg.sendBufLen + 4;
	}


	static writeShort(n) {
		Msg.sendBufDV.setInt16(Msg.sendBufLen, n);
		Msg.sendBufLen = Msg.sendBufLen + 2;
	}

	static writeByte(n) {
		Msg.sendBufDV.setInt8(Msg.sendBufLen, n);
		Msg.sendBufLen = Msg.sendBufLen + 1;
	}

	static writeString(str) {
		var oldPos = Msg.sendBufLen
		Msg.writeShort(0)
		var totalByte = 0
		var strLen = str.length
		for (var i = 0; i < strLen; ++i) {
			var t = str.charCodeAt(i)
			if (t < 128) {
				totalByte = totalByte + 1
				Msg.writeByte(t)
			}
			else if (t < 2048) {
				totalByte = totalByte + 2
				Msg.writeByte(t >> 6 | 192)
				Msg.writeByte(t & 63 | 128)
			}
			else if (t < 65536) {
				totalByte = totalByte + 3
				Msg.writeByte(t >> 12 | 224)
				Msg.writeByte(t >> 6 & 63 | 128)
				Msg.writeByte(t & 63 | 128)
			}
			else {
				throw "error";
			}
		}
		Msg.sendBufDV.setInt16(oldPos, totalByte);
	}

	static send(packetID) {
		var ab = new Uint8Array(Msg.sendBufLen)
		for (var i = 0; i < Msg.sendBufLen; ++i) {
			ab[i] = Msg.sendBufDV.getInt8(i);
		}

			Msg.websocket.send(ab.buffer);
	}

	static close() {
	    if (Msg.websocket) {
	        Msg.websocket.close();
	    }
	    if (Msg.websocketM) {
	        Msg.websocketM.close();
	    }
	    Msg.isConnect = false;
	    Msg.isConnecting = false;
	    Msg.isConnectM = false;
	    Msg.isConnectingM = false;
	}
  
    static CG_ASK_LOGIN(account: string, timestamp: number, authkey: string, lang: string, region: string, ip: string, params: string)
	{
		console.log("发送登录消息",Msg.websocket.readyState,Msg.isConnect);
		if (Msg.isConnect != true || Msg.websocket.readyState != 1) return;
		Msg.sendBufLen = 4;
		Msg.writeString(account);
		Msg.writeInt(timestamp);
		Msg.writeString(authkey);
		Msg.writeString(lang);
		Msg.writeString(region);
		Msg.writeString(ip);
		Msg.writeString(params);
		Msg.sendBufDV.setInt16(2, 62);	
		Msg.sendBufDV.setInt16(0, Msg.sendBufLen - 4);
		Msg.send(62);
		console.log("发送完了断开连接");
        Msg.close();  // 主动断开连接
	}

}