import { BJ_Casino_Data } from "./BJ_Casino_Data";
import { NetConnector } from "./Engine/CatanEngine/NetManagerV2/NetConnector";
import { Tools } from "./Tools";

export class BJ_ServerState {
	//#region Lifecycle

	public BJ_Casino: BJ_Casino_Data;

	public ID: number;

	//#endregion

	//#region private

	private _conn: NetConnector = null;

	private _client: any;

	//#endregion

	//#region Lifecycle

	/**
	 *
	 */
	constructor(client: any) {
		this._client = client;
		this.BJ_Casino = client.BJ_Casino;
		this.ID = client.ID;
		this.onLoad();
	}

	public async onLoad(): Promise<void> {
		await this.ConnectServer();
	}

	//#endregion

	//#region 網路相關

	/** 連線 */
	public async ConnectServer(): Promise<void> {
		let serverList = this.BJ_Casino.Config.ServerList;
		let server = serverList[this.ID];
		if (!server) {
			return;
		}
		const Name: string = server.name;
		const Host: string = server.host;
		const Port: string = server.port;
		this._client.Name.value = Name;
		this._client.Host.value = Host;
		this._client.Port.value = Port;
		await this.ConnectAsync(Host, +Port);
	}

	/** 連線(目前沒有重連機制) */
	public async ConnectAsync(host: string, port: number): Promise<void> {
		let self = this;
		var url: string = "https://api.ipify.org/?format=json";
		var xhr: XMLHttpRequest = new XMLHttpRequest();
		let ip: string = "";
		xhr.onreadystatechange = function (): void {
			if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 400)) {
				ip = JSON.parse(xhr.responseText)["ip"];
			}
		};
		xhr.open("GET", url, true);
		xhr.send();
		console.log("[事件]準備連線...");
		while (ip === "") {
			await Tools.Sleep(1);
		}

		let checkHttp: string = "";
		let ws: string = "";
		let index: number = host.indexOf("https://");
		if (index != -1) {
			checkHttp = "https";
			host = host.replace("https://", "");
		} else {
			checkHttp = window.location.href.substring(0, 5);
			host = host.replace("http://", "");
		}
		if (true) {
			console.log("[事件]checkHttp=", checkHttp, host, port);
		}
		if (checkHttp != "https") {
			ws = `ws://${host}:${port}/?ip=${ip}`;
		}
		else {
			ws = `wss://${host}:${port}/?ip=${ip}`;
		}

		let socket = new WebSocket(ws);

		socket.onopen = function (e) {
			console.log(`[事件] [${self._client.Name.value}] 連線狀態: true`);
			self._client.IsConnect.value = "true";
		};

		socket.onmessage = function (event) {
			// alert(`[message] Data received from server: ${event.data}`);
		};

		socket.onclose = function (event) {
			// if (event.wasClean) {
			// 	// alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
			// } else {
			// 	// 例如服务器进程被杀死或网络中断
			// 	// 在这种情况下，event.code 通常为 1006
			// 	// alert('[close] Connection died');
			// }
		};

		socket.onerror = function (error) {
			// alert(`[error] ${error["message"]}`);
			self._client.IsConnect.value = "無回應";
		};
	}

	//#endregion
}
