import './NewGame.css'
import React, { useContext } from 'react';
import { GamesContext } from '../../../context/games';

import DropdownList from '../../../components/DropdownList';
import { WhiteStone, BlackStone } from '../../../components/Checkers';

export default function NewGame({ players, onSelectPlayer }) {
    const games = useContext(GamesContext);

    /*
     * Name options
     */
    const nameOptions = !players.leaderboard.table
        ? [<option key='loading' value='…'>…loading</option>]
        : Object.keys(players.leaderboard.table).map(playerName =>
            <option key={playerName} value={playerName}>
                {players.isCurrentUser(playerName) ? 'You' : playerName}
            </option>)

    const whiteOptions = Array(nameOptions)
    whiteOptions.push(<option key='default' value=''>{'white player …'}</option>)

    const blackOptions = Array(nameOptions)
    blackOptions.push(<option key='default' value=''>{'black player …'}</option>)

    /*
     * Radiobutton
     */
    const radioButton = (whitePlayer, blackPlayer) => {
        if (whitePlayer !== '' && whitePlayer === games.newGame.blackPlayer) {
            blackPlayer = '';
        }
        if (blackPlayer !== '' && blackPlayer === games.newGame.whitePlayer) {
            whitePlayer = '';
        }

        onSelectPlayer(whitePlayer, blackPlayer);
    }

    const setWhitePlayer = (name) => {
        radioButton(name, games.newGame.blackPlayer);
    }

    const setBlackPlayer = (name) => {
        radioButton(games.newGame.whitePlayer, name);
    }

    /*
     * The Component
     */
    return (
        <div className='NewGame'>
            <WhiteStone />
            <DropdownList selected={games.newGame.whitePlayer} onSelect={setWhitePlayer} optionsList={whiteOptions} />
            <i>- vs -</i>
            <DropdownList selected={games.newGame.blackPlayer} onSelect={setBlackPlayer} optionsList={blackOptions} />
            <BlackStone />
        </div>
    )
}