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

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

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

        function sendGameReady() {
            ws.sendGameReady(game.id);
        }

        function sendInstanceState(instanceId) {
            if (!instanceId) return false;
            return ws.sendInstanceState(instanceId);
        }

        return {
            game,
            account,
            animating,
            sendInstanceState,
            sendGameReady,
        };
    },

    function receiveDispatch(dispatch) {
        function quit() {
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
        }

        return { quit };
    }

);

function GameFooter(props) {
    const {
        game,
        account,
        animating,

        quit,
        sendGameReady,
        sendInstanceState,
    } = props;

    if (!game) return false; // ???

    const playerTeam = game.players.find(t => t.id === account.id);

    function quitClick() {
        sendInstanceState(game.instance);
        quit();
        return true;
    }

    const quitBtn = (
        <button
            onClick={quitClick}>
            Back
        </button>
    );

    const readyBtn = (
        <button
            disabled={animating}
            class={`${playerTeam.ready ? 'ready' : ''} ready-btn`}
            onClick={sendGameReady}>
            Ready
        </button>
    );

    const zero = Date.parse(game.phase_start);
    const now = Date.now();
    const end = Date.parse(game.phase_end);
    const timerPct = ((now - zero) / (end - zero) * 100);
    const displayPct = game.phase === 'Finished' || !game.phase_end
        ? 0
        : Math.min(timerPct, 100);

    const displayColour = playerTeam.ready
        ? 'forestgreen'
        : timerPct > 80
            ? 'red'
            : 'whitesmoke';

    const timerStyles = {
        width: `${displayPct}%`,
        background: displayColour,
    };

    const timer = game.phase_end
        ? (
            <div class="timer-container">
                <div class="timer" style={timerStyles} >&nbsp;</div>
            </div>
        )
        : null;

    return (
        <footer>
            {timer}
            {game.phase === 'Finished' && quitBtn }
            {game.phase === 'Skill' && readyBtn }
        </footer>
    );
}

module.exports = addState(GameFooter);
