import MainControl from "@/Common/MainControl/MainControl";
import CSMessage from "@/Common/Message/CSMessage";
import { CoroutineV2 } from "@/Engine/CatanEngine/CoroutineV2/CoroutineV2";
import { INetResponse } from "@/Engine/CatanEngine/NetManagerV2/Core/INetResponse";
import { BusinessEnum } from "@/_BusinessTypeSetting/BusinessTypeSetting";
import { useGameItems } from "@/context/GameItemsContext";
import { AccountLoginRequest } from "@/define/Request/AccountRequest";
import { CommonAccountResponse, LineLoginRequest } from "@/define/Request/RegisterRequest";
import { Button, Cascader } from "antd";
import TextArea from "antd/es/input/TextArea";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";

interface Option {
	value: string;
	label: string;
	children?: Option[];
}

const Login = () => {
	const { onLoad, player, setPlayer } = useGameItems();
	const navigate = useNavigate();
	const serverType: typeof BusinessEnum.ServerType = BusinessEnum.ServerType;
	const [type, setType] = useState<number>(BusinessEnum.ServerType.Internal_Dev);
	const [isLogin, setIsLogin] = useState<boolean>(false);
	const a = "eyJhbGciOiJIUzI1NiJ9.hoaQl5V6Ni6G3xXJXSADO-aS2fopaAd8lA-K6UkTUbhU46l1B5JU2TxINvsRQPmNE1TzKPc0MD5dyFOEJmo8gpGtRWsMWiyzekENR6QwJluQa2nL83QNZaif8BhEff1vm0F_TOAA2ENDiaY7VnkeLHB-Dv3KyRo5AEAmYVFWK_A.k1rj5BHgPKCVvI7sDjBwb6dGOl4OH3131NIr5vxVrGA";
	const [token, SetToken] = useState(a);
	const options: Option[] = [];
	for (let i = 0, names: string[] = Object.keys(serverType); i < names.length; i++) {
		const key: string = names[i];
		if (!Number.isNaN(+key)) {
			options.push({
				value: key,
				label: serverType[key],
			});
		}
	}

	async function onClickLogin() {
		if (!token) {
			CSMessage.CreateYesMsg("請輸入token");
			return;
		}
		setIsLogin(true);
		await onLoad(type);
		CoroutineV2.Single(login()).Start();
	}

	function* login() {
		yield* MainControl.Instance.ConnectAsync();
		yield* registerLineLogin();
	}

	function* registerLineLogin() {
		let req: LineLoginRequest = new LineLoginRequest(token);
		yield req.SendAsync(true);
		let resp: INetResponse<CommonAccountResponse> = req.Result;
		if (!resp.IsValid) {
			//取得帳號失敗直接斷開SOCKET
			if (resp.Status != 12) {
				const msg: string = "Line Info Error. Error Code:" + req.Result.Status;
				CSMessage.CreateYesMsg(msg);
				setIsLogin(false);
				return;
			}
			console.warn("LINE帳號無綁定");
			setIsLogin(false);
			return;
		}
		yield* serverAccountLogin(resp.Data.id, resp.Data.pw);
	}

	/** 遊戲帳號登入取得玩家資料.統一登入時在刪除需要刪除的資料 */
	function* serverAccountLogin(a: string, pw: string, partner: string = null): IterableIterator<any> {
		let hasAP: boolean = (a && a != "null" && a != "undefined" && pw && pw != "null" && pw != "undefined");
		if (!hasAP) {
			CSMessage.CreateYesMsg("沒有帳號或密碼.請確認回傳接值.");
			setIsLogin(false);
			return;
		}
		let req: AccountLoginRequest = new AccountLoginRequest(a, pw, partner);
		yield req.SendAsync(true);
		let resp: INetResponse<any> = req.Result;
		if (!resp.IsValid) {
			CSMessage.CreateYesMsg("Login Account Error! Error Code : " + resp.Status);
			setIsLogin(false);
			return;
		}
		setPlayer({
			...player,
			...resp.Data,
			token: token
		});
		navigate(`/lobby/`);
	}

	return (
		<>{!isLogin &&
			<div style={boxStyle}>
				<div style={boxStyle2}>
					<Cascader defaultValue={[BusinessEnum.ServerType[BusinessEnum.ServerType.Internal_Dev]]} options={options} onChange={(v: string[]) => setType(+v[0])} />
					<br />
					Token： <TextArea rows={4} value={token} onChange={e => SetToken(e.target.value)} />
					<br />
					<Button type="primary" onClick={onClickLogin}>登入</Button>
				</div>
			</div>
		}</>
	);
};

export default Login;

const boxStyle: React.CSSProperties = {
	display: "flex",
	justifyContent: "center",
};

const boxStyle2: React.CSSProperties = {
	width: "50%",
	height: "100vh",
	display: "flex",
	alignItems: "center",
	justifyContent: "center",
	flexDirection: "column"
};