import { Accessor, createContext, createResource, Show } from "solid-js";
import { GameState } from "../../../shared/types/cards";
import api from "../api";
import Hand from "./Hand";
import Pile from "./Pile";

export const GameContext = createContext<{
	gameState: Accessor<GameState | undefined>;
	setGameState: (state: GameState) => Promise<any>;
}>();

export default (props: { instanceId: number }) => {
	const [gameState, { refetch }] = createResource(() =>
		api
			.gameState({ gameId: props.instanceId.toString() })
			.get()
			.then((res) => res.data as GameState)
	);

	const setGameState = (state: GameState) =>
		api
			.gameState({ gameId: props.instanceId.toString() })
			.put({
				gameState: state,
			})
			.then(refetch);

	return (
		<GameContext.Provider value={{ gameState, setGameState }}>
			<Show when={gameState() != undefined}>
				<div
					class="full column center"
					style={{ "row-gap": "20px", "font-size": "32px" }}
				>
					<div class="full center">
						<Pile
							pile={gameState()!.deck}
							style={{ cursor: "pointer" }}
							onClick={() => {
								const [drawn, ...rest] = gameState()!.deck;
								setGameState({
									deck: rest,
									hand: [drawn, ...gameState()!.hand],
								});
							}}
						/>
					</div>
					<Hand hand={gameState()!.hand} />
				</div>
			</Show>
		</GameContext.Provider>
	);
};
