import CSMessage from "@/Common/Message/CSMessage";
import { CoroutineV2 } from "@/Engine/CatanEngine/CoroutineV2/CoroutineV2";
import { INetResponse } from "@/Engine/CatanEngine/NetManagerV2/Core/INetResponse";
import CSSettingsSDV3 from "@/FormTableSD/CSSettingsSDV3";
import BusinessTypeSetting from "@/_BusinessTypeSetting/BusinessTypeSetting";
import Image from "@/components/Image/Image";
import { useGameItems } from "@/context/GameItemsContext";
import { GameLaunchRequest, GameLeaveRequest, RpcGameLaunchResponse } from "@/define/Request/GameRequest";
import { SlotData } from "@/define/gameData";
import { Button, Flex } from "antd";
import { useEffect, useState } from "react";
import SDGame from "./SDGame";

const SlotList = () => {
	const { gameData, setGameData } = useGameItems();
	const { slotData, slotList, nowSlotId } = gameData;
	const [isGameIn, setIsGameIn] = useState<boolean>(false);
	const [gameUrl, setGameUrl] = useState<string>("");

	function onLoad() {

	}

	function* onClickSlotIn(slotId: number): IterableIterator<any> {
		const data: SlotData = slotData[slotId];
		const [componyID] = data;
		const req: GameLaunchRequest = new GameLaunchRequest(componyID, slotId);
		yield req.SendAsync();
		const resp: INetResponse<RpcGameLaunchResponse> = req.Result;
		if (!resp.IsValid) {
			if (resp.Status === 18) {
				CSMessage.CreateYesMsg(CSSettingsSDV3.prototype.CommonString(16));
			}
			return;
		}
		setIsGameIn(true);
		const url: string = resp.Data;
		setGameData({
			...gameData,
			nowSlotId: slotId
		});
		if (componyID === 2) {
			setGameUrl(url);
		}
		else {
			window.open(url, "_blank");
		}
	}

	function onClickSlotOut() {
		const gameLeaveReq: GameLeaveRequest = new GameLeaveRequest(nowSlotId);
		gameLeaveReq.Send();
		setGameUrl("");
		setIsGameIn(false);
	}

	useEffect(() => {
		onLoad();
	}, []);

	return (<>
		{isGameIn
			? <>{gameUrl
				? <SDGame gameUrl={gameUrl} onClickSlotOut={onClickSlotOut} />
				: <Flex gap="small" wrap="wrap">
					<Button type="primary" onClick={onClickSlotOut}>離開機台</Button>
				</Flex>}</>

			: <div style={contentStyle}>
				<Flex gap="small" wrap="wrap">
					{slotList.map((slotId: number, index: number) =>
						<Image key={index} width={80} height={80} src={`${BusinessTypeSetting.UseDownloadUrl}game/${slotId}/s`}
							onClick={() => { CoroutineV2.Single(onClickSlotIn(slotId)).Start(); }} style={{ cursor: "pointer" }} />
					)}
				</Flex>
			</div>
		}
	</>);
};

export default SlotList;

const contentStyle: React.CSSProperties = {
	fontSize: "1rem",
	minHeight: 120,
	lineHeight: "120px",
	color: "#000000",
	display: "flex",
	textAlign: "center",
	flexDirection: "column",
	justifyContent: "center",
	width: "100%"
};