import { Accessor, createContext, createResource, Show } from "solid-js";
import {
	GameState,
	Action,
	vGameState,
	PlayerView,
} from "../../../server/src/games/simple";
import api from "../api";
import Hand from "./Hand";
import Pile from "./Pile";

export const GameContext = createContext<{
	view: Accessor<PlayerView | undefined>;
	submitAction: (action: Action) => Promise<any>;
}>();

export default (props: { instanceId: string }) => {
	const [view, { mutate }] = createResource(() =>
		api
			.simple(props)
			.get()
			.then((res) => res.data as PlayerView)
	);
	const submitAction = (action: Action) =>
		api
			.simple(props)
			.post({ action })
			.then((res) => res.status == 200 && mutate(res.data as PlayerView));

	return (
		<GameContext.Provider value={{ view, submitAction }}>
			<Show when={view.latest != undefined}>
				<div
					class="full column center"
					style={{ "row-gap": "20px", "font-size": "32px" }}
				>
					<div class="full center">
						<Pile
							count={view.latest!.deckCount}
							style={{ cursor: "pointer" }}
							onClick={() => submitAction({ type: "draw" })}
						/>
					</div>
					<Hand hand={view.latest!.myHand} />
				</div>
			</Show>
		</GameContext.Provider>
	);
};
