import { CoroutineV2 } from "@/Engine/CatanEngine/CoroutineV2/CoroutineV2";
import { INetResponse } from "@/Engine/CatanEngine/NetManagerV2/Core/INetResponse";
import { gameSync } from "@/utils/setRPCData";
import MainControl from "../MainControl/MainControl";
import CSMessage from "../Message/CSMessage";

export default class MainControlData {

	/**
	Normal = 0,         //一般斷線or登出
	RpcError = 1,       //RPC錯誤
	SystemError = 2,    //系統錯誤
	UserError = 3,      //使用者造成的錯誤
	DbaError = 4,       //query時回傳錯誤
	SendBufferError = 5, //儲存傳送資料的buff錯誤
	Kick = 6,            //指定踢除
	ConnectLimit = 7,    //連線限制
	RequireHardLimit = 8,   //機台請求逾時
	SignalWallet = 9,
	RepeatLogin = 101, //重覆登入
	LoginFailed = 102, //登入失敗
	AppVerError = 103, //Client版本過舊
	Maintain = 104,    //維護中
	Ban = 105,         //帳號鎖定
	SlotClose = 106,   //機台關閉
	ResourceWait = 107, //使用者資料尚未寫入
	IsDelete = 108, // 被刪除的帳號
	Delete = 109, // 刪除主動斷線
	SafeDisconnect = 201,    // 安全離線
	*/
	private _disconnectErrorType: number = null;

	constructor() {
		MainControl.DataReceivedEvent.AddCallback(this._dataReceivedEvent, this);
	}
	private _dataReceivedEvent(param: any[] = null): void {
		let type: MainControl.DataType = param[0];
		let data: any = param[1];
		switch (type) {
			case MainControl.DataType.ServerData:
				this._serverData(data);
				break;
			case MainControl.DataType.NetDisconnected:
				this._netDisconnected();
				break;
			default:
				break;
		}
	}
	// =======================================================================================
	/** SERVER主動通知 */
	private _serverData(resp: INetResponse<any>): void {
		if (resp.IsValid) {
			switch (resp.Method) {
				case "game.sync": {
					CoroutineV2.Single(gameSync()).Start();
					break;
				}
				case "system.disconnect": {
					this._disconnectErrorType = +resp.Data["c"];
					break;
				}
				default:
					break;
			}
		} else {
			switch (resp.Method) {
				// case "": {
				// 	break;
				// }
				default:
					break;
			}
		}
	}
	// =======================================================================================
	/** SOCKET斷線 */
	private _netDisconnected(): void {
		console.debug("Disconnected Error Type : " + this._disconnectErrorType);
		let str: string = null;
		// if (this._disconnectErrorType < 10 && this._disconnectErrorType >= 0) {
		// 	str = CSSettingsV3.prototype.CommonString(55 + this._disconnectErrorType);
		// } else if (this._disconnectErrorType > 100 && this._disconnectErrorType < 110) {
		// 	str = CSSettingsV3.prototype.CommonString(65 + this._disconnectErrorType - 101);
		// } else {
		// 	str = "Server Disconnected";
		// }
		str = "Server Disconnected";
		CSMessage.CreateYesMsg(
			str,
			this._disconnectedReload
		);
	}

	private _disconnectedReload(): void {
		window.location.reload();
	}

	// =======================================================================================
}