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

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

const PlayerBox = require('./player.box');

const addState = connect(
    function receiveState(state) {
        const {
            ws,
            instance,
            account,
            animating,
        } = state;

        function sendReady() {
            document.activeElement.blur();
            return ws.sendInstanceReady(instance.id);
        }

        function sendAbandon() {
            return ws.sendInstanceAbandon(instance.id);
        }

        return {
            sendAbandon,
            instance,
            sendReady,
            account,
            animating,
        };
    },
    function receiveDispatch(dispatch) {
        function leave() {
            dispatch(actions.setNav('play'));
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
        }

        return { leave };
    }
);

function Controls(args) {
    const {
        account,
        sendAbandon,
        instance,
        sendReady,
        leave,
    } = args;

    if (!instance) return false;

    const opponent = instance.players.find(t => t.id !== account.id);
    const player = instance.players.find(t => t.id === account.id);

    const zero = Date.parse(instance.phase_start);
    const now = Date.now();
    const end = Date.parse(instance.phase_end);
    const timerPct = instance.phase_end
        ? ((now - zero) / (end - zero) * 100)
        : 100;

    const displayColour = !instance.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 ready = instance.phase !== 'Finished'
        ? <button class="ready" onClick={() => sendReady()}>Ready</button>
        : <button class="ready" onClick={leave}>Leave</button>

    const abandon = instance.phase !== 'Finished' ? sendAbandon : false;
    return (
        <aside>
            {timer}
            <div class="controls">
                <PlayerBox player={opponent} />
                {ready}
                <PlayerBox player={player} isPlayer={true} abandon={abandon}/>
            </div>
        </aside>
    );
}

module.exports = addState(Controls);
