const preact = require('preact');
const { connect } = require('preact-redux');

const actions = require('../actions');

const PlayerBox = require('./player.box');
const Chat = require('./chat');
const GameCtrlButtons = require('./game.ctrl.btns');
const GameCtrlTopButtons = require('./game.ctrl.btns.top');

const addState = connect(
    function receiveState(state) {
        const {
            animating,
            game,
            account,
            chatShow,
            instanceChat,
        } = state;

        return {
            animating,
            game,
            account,
            chatShow,
            instanceChat,
        };
    },
);

function Controls(args) {
    const {
        animating,
        account,
        game,
        chatShow,
        instanceChat,
    } = args;

    if (!game) return false;

    const opponent = game.players.find(t => t.id !== account.id);
    const player = game.players.find(t => t.id === account.id);
    const zero = Date.parse(game.phase_start);
    const now = animating ? zero : Date.now();
    const end = Date.parse(game.phase_end);

    const timerPct = game.phase_end
        ? ((now - zero) / (end - zero) * 100)
        : 100;

    const displayColour = !game.phase_end
        ? '#222'
        : player.ready
            ? 'forestgreen'
            : timerPct > 80
                ? 'red'
                : 'whitesmoke';

    const timerStyles = {
        height: `${timerPct > 100 ? 100 : timerPct}%`,
        background: displayColour,
    };

    const timer = (
        <div class="timer-container">
            <div class="timer" style={timerStyles} >&nbsp;</div>
        </div>
    );

     const bottom = chatShow
        ? <Chat />
        : <PlayerBox player={player} isPlayer={true} chat={instanceChat && instanceChat[player.id]} />;

    return (
        <aside>
            {timer}
            <div class="controls instance-ctrl">
                <GameCtrlTopButtons />
                <PlayerBox player={opponent} chat={instanceChat && instanceChat[opponent.id]}/>
                {bottom}
                <GameCtrlButtons />
            </div>
        </aside>
    );
}

module.exports = addState(Controls);
