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

const PlayerBox = require('./player.box');
const Chat = require('./chat');
const InstanceCtrlBtns = require('./instance.ctrl.btns');
const InstanceCtrlTopBtns = require('./instance.ctrl.top.btns');

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

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

        return {
            chatShow,
            instance,
            instanceChat,
            account,
        };
    },
);

function Controls(args) {
    const {
        account,
        instance,
        instanceChat,
        chatShow,
    } = 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 !== 'Finished' && instance.phase_end
        ? ((now - zero) / (end - zero) * 100)
        : 100;

    const displayColour = !instance.phase_end || instance.phase === 'Finished'
        ? '#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">
                <InstanceCtrlTopBtns />
                <PlayerBox player={opponent} chat={instanceChat && instanceChat[opponent.id]}/>
                {bottom}
                <InstanceCtrlBtns />
            </div>
        </aside>
    );
}

module.exports = addState(Controls);
