import React from 'react';
import User from './user';

class UserControl extends React.Component {
    constructor() {
        super();

        /**
         * activePlayer - red: 0, blue: 1
         * @type {{activePlayer: boolean, mines: number, bombSelected: boolean, foundMines: boolean}}
         */
        this.state = {
            activePlayer: false,
            mines: 51,
            bombSelected: false,
            foundMines: false
        };
    }

    youCanSelectBomb(activePlayer, clickedPlayer) {
        return this.refs[activePlayer].state.haveBomb &&
            this.refs[activePlayer].state.enabledBomb &&
            this.state.activePlayer === clickedPlayer;
    }

    onClickBombSelector(clickedPlayer) {
        let activePlayer = this.state.activePlayer ? 'blue' : 'red';

        if (this.youCanSelectBomb(activePlayer, clickedPlayer)) {
            this.state.bombSelected = !this.state.bombSelected;

            if (!this.state.bombSelected) {
                this.props.bombClear();
            }
        }
    }

    getResignClass(webPlayer) {
        let activePlayer = this.state.activePlayer === 1 ? 'blue' : 'red';
        return "resign" + (webPlayer !== activePlayer ? ' disabled' : '');
    }

    activeMines() {
        return "active-mines" + (this.state.foundMines ? ' found-mine' : '');
    }

    render() {
        return (
            <div className="users">
                <User ref="blue"
                      color="blue"
                      webPlayer={this.props.webPlayer}
                      active={this.state.activePlayer === 1}
                      onClickBombSelector={this.onClickBombSelector.bind(this, 1)}/>
                <div className="active-mines-container">
                    <i className="fa fa-star"></i>
                    <div className={this.activeMines()}>
                        <div className="active-mines-nbr">{this.state.mines}</div>
                        <div className="active-mines-shine"></div>
                    </div>
                    <i className="fa fa-star"></i>
                </div>
                <div className="clear"></div>
                <User ref="red"
                      color="red"
                      webPlayer={this.props.webPlayer}
                      active={this.state.activePlayer === 0}
                      onClickBombSelector={this.onClickBombSelector.bind(this, 0)}/>
                <button className={this.getResignClass(this.props.webPlayer)} onClick={this.props.resign}>
                    <div className="resign-shine"></div>
                    Resign
                </button>
            </div>
        );
    }
}

export default UserControl;
