import React, { useContext } from 'react';
import { GamesContext } from '../../../context/games';
import Wobler from '../../../components/Wobler';



export default function Create({ isCurrentUser }) {
    const newGameCtx = useContext(GamesContext).newGame;

    const hasPlayers = checkPlayers(newGameCtx);
    const hasCurrentUser = checkCurrentUser(newGameCtx, isCurrentUser);

    const pushNewGame = () => {
        if (!hasPlayers)
            return alert("Black and White players must be selected for the game");

        if (!hasCurrentUser)
            return alert("You must be one of the selected players");

        if (newGameCtx.pushing)
            return; // current request is still being processed

        console.log("send request");
    }

    return (
        <button className={'Create'
            + (hasPlayers && hasCurrentUser ? ' ready' : '')
        }
            onClick={pushNewGame}
        >
            <Wobler text="Create" dance={newGameCtx.pushing} />
        </button>
    )
}

function checkPlayers({ whitePlayer, blackPlayer }) {
    return whitePlayer && blackPlayer
        && whitePlayer !== blackPlayer;
}

function checkCurrentUser({ whitePlayer, blackPlayer }, isCurrentUser) {
    return isCurrentUser(whitePlayer) || isCurrentUser(blackPlayer);
}