import { Component, createEffect, createSignal, Match, Switch } from 'solid-js';
import createWebsocket from '@solid-primitives/websocket';
import { wsUrl } from './constants';
import Spinner from './components/Spinner';
import Welcome from './components/Welcome';
import { Board as BoardData, Move, ServerChessEvent } from './events';
import Board from './components/Board';

interface Props {
  gameId: string;
}

const App: Component<Props> = (props) => {
  const [board, setBoard] = createSignal<BoardData>(Array(64).fill(null));
  const [possibleMoves, setPossibleMoves] = createSignal<Move[]>([]);

  function handleEvent(e: MessageEvent<string>) {
    const data = JSON.parse(e.data);
    const event = ServerChessEvent.parse(data);
    if (event.event === 'BoardUpdate') {
      console.log(event.data.board);
      setBoard(event.data.board);
    } else if (event.event === 'PossibleMoves') {
      console.log(event.data.moves);
      setPossibleMoves(event.data.moves);
    }
  }

  createEffect(() => {
    console.log('board is now', board());
  });

  createEffect(() => {
    console.log('moves is now', possibleMoves());
  });

  const [connect, disconnect, send, state, socket] = createWebsocket(wsUrl(props.gameId), handleEvent, console.error);

  function makeMove(move: Move) {
    send(JSON.stringify({
      event: 'MakeMove',
      data: {
        move,
      },
    }));
  }

  return <Switch fallback={<><h1>Hello, World!</h1><Spinner /></>}>
    <Match when={state() === WebSocket.CLOSED}>
      <Welcome gameId={props.gameId} joinGame={() => connect()} />
    </Match>
    <Match when={state() === WebSocket.CONNECTING}>
      <Spinner />
    </Match>
    <Match when={state() === WebSocket.OPEN}>
      <Board board={board} moves={possibleMoves} makeMove={makeMove} />
    </Match>
  </Switch>
};

export default App;
