import { Action } from "@/Engine/CatanEngine/CSharp/System/Action";
import { INetResponse } from "@/Engine/CatanEngine/NetManagerV2/Core/INetResponse";
import { NetConnector } from "@/Engine/CatanEngine/NetManagerV2/NetConnector";
import { NetManager } from "@/Engine/CatanEngine/NetManagerV2/NetManager";
import { TableManager } from "@/Engine/CatanEngine/TableV3/TableManager";
import BaseSingleton from "@/Engine/Utils/Singleton/BaseSingleton";
import BusinessTypeSetting from "@/_BusinessTypeSetting/BusinessTypeSetting";
import { Tools } from "@/utils/Tools";

export class MainControl extends BaseSingleton<MainControl>() {
	/** 每次啟動APP */
	public IsFirstEnteringLobby: boolean = true;
	// /** 登入成功判斷 */
	// public IsLogin: boolean = false;
	// /** 選桌頁內的機台號碼 */
	// public TableID: number = 0;
	/** 最後遊玩的一個廠商 */
	public LastPlayComponyID: number = 0;
	/** 最後遊玩的一個遊戲 */
	public LastPlayGameID: number = 0;
	// /** 主動斷線=字串.被動斷線=null(因為SERVER有時候會先主動斷線所以有的要預先設定字串)*/
	// public IsLogoutStr: string = null;
	public IsInGame: boolean = false;
	/** 現在時間 */
	public get NowTime(): number { return Date.now(); }

	public static readonly DataReceivedEvent: Action<any[]> = new Action<any[]>();

	/** 連線控制 */
	private _conn: NetConnector = null;

	//#region 網路相關

	/**連線(目前沒有重連機制) */
	public * ConnectAsync() {
		if (NetManager.IsConnected) {
			return;
		}
		this._conn = new NetConnector(BusinessTypeSetting.UseHost, BusinessTypeSetting.UsePort);
		this._conn.OnDataReceived.AddCallback(this._onNetDataReceived, this);
		this._conn.OnDisconnected.AddCallback(this._onNetDisconnected, this);
		NetManager.Initialize(this._conn);
		console.log("[socket] connecting...");
		// 同個connector要再次連線, 可以不用叫CasinoNetManager.Initialize(), 但要先叫CasinoNetManager.Disconnect()
		yield NetManager.ConnectAsync();
	}

	/**只要連線中斷不管主被動都會走到這裡 */
	private _onNetDisconnected() {
		console.warn("[socket] Disconnected");
		this._conn.OnDataReceived.RemoveAllCallbacks();
		MainControl.DataReceivedEvent.DispatchCallback([MainControl.DataType.NetDisconnected]);
	}

	/**RPC回傳.若協定錯誤斷線.原因也會在這裡收到 */
	private _onNetDataReceived(resp: INetResponse<any>) {
		MainControl.DataReceivedEvent.DispatchCallback([MainControl.DataType.ServerData, resp]);
	}


	//#region DownloadForm Function

	/**
	 * 載入外載表設定檔
	 * @param formType FormType
	 */
	public static async DownloadForm(formType: DownloadForm.FormType): Promise<void> {
		if (DownloadForm.DownloadFormData.DownloadSuccess.has(formType)) {
			console.warn(`CSSettingsV3 ${formType} 已經載過`);
			return;
		}
		DownloadForm.DownloadFormData.DownloadSuccess.set(formType, true);
		let needForm: string[] = DownloadForm.DownloadFormData[`${formType}Form`];
		let parallel: Promise<void>[] = [];
		for (let i: number = 0; i < needForm.length; i++) {
			parallel.push(this.DownloadFormSetting(needForm[i]));
		}
		// set Form
		await Promise.all(parallel);
	}

	/**
	 * 載入外載表設定檔
	 * @param formname 設定檔名稱
	 */
	public static async DownloadFormSetting(formname: string): Promise<void> {
		// http://patch-dev.online-bj.com/shared/jsons/slot_050.json
		let fileUrl: string = `${formname}.json`;
		if (import.meta.env.PROD) {
			// fileUrl = "https://patch.sdegaming.com/slot2/patch/_Release/shared/jsons/" + fileUrl;
			// fileUrl = "https://sd2-dev-patch.sdegaming.com/_Debug/shared/jsons/" + fileUrl;
			fileUrl = "http://192.168.5.45:5001/shared/jsons/" + fileUrl;
			// fileUrl = "https://patch.sdegaming.com/slot2/patch/_Release/shared/jsons/" + fileUrl;
			// fileUrl = "http://patch-dev.online-bj.com/shared/jsons/" + fileUrl;
			// fileUrl = "http://jianmiau.tk/_BJ_Source/BJ-Internal-Dev/shared/jsons/" + fileUrl;
		} else {
			fileUrl = "./shared/jsons/" + fileUrl;
		}
		fileUrl = fileUrl + "?v=" + Date.now();
		let isDownloading: boolean = true;
		let xhr: XMLHttpRequest = new XMLHttpRequest();
		// xhr.withCredentials = true;
		xhr.onreadystatechange = function (): void {
			if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 400)) {
				let res: any = {};
				res.json = JSON.parse(xhr.responseText);
				res.name = formname;
				TableManager.AddJsonAsset(res);
				isDownloading = false;
			}
		};
		xhr.open("GET", fileUrl);
		xhr.send();
		while (isDownloading) {
			await Tools.Sleep(100);
		}
	}

	//#endregion
}

export module MainControl {
	export enum DataType {
		ServerData,
		ChangeDire,
		NetDisconnected,
	}
}

export default MainControl;

//#region DownloadForm

export module DownloadForm {
	export enum FormType {
		Formread = "formread",
	}

	export class DownloadFormData {

		/** 已下載的表 */
		public static DownloadSuccess: Map<string, boolean> = new Map<string, boolean>();

		/** Bag需要的表(xxxx.json) */
		public static formreadForm: string[] = ["slotset"];
	}
}

//#endregion