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

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

const addState = connect(
    function receiveState(state) {
        const { ws, instance, player, nav } = state;

        function sendInstanceReady() {
            return ws.sendInstanceReady(instance.id);
        }

        return { player, instance, sendInstanceReady, nav };
    },

    function receiveDispatch(dispatch) {
        function setNav(v) {
            return dispatch(actions.setNav(v));
        }

        return {
            setNav,
        };
    }
);

function Instance(args) {
    const {
        instance,
        player,

        sendInstanceReady,
    } = args;
    if (!instance) return false;
    const rdyClasses = `ready-btn ready`;
    const readyInfo = instance.phase === 'Lobby'
        ? 'lobbyReady'
        : 'ready';

    const readyBtn = (
        <button
            class={rdyClasses}
            onClick={() => sendInstanceReady()}>
            Ready
        </button>
    );

    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)
        : 0;

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

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

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

    return (
        <footer id="footer">
            {timer}
            {readyBtn}
        </footer>
    );
}

module.exports = addState(Instance);
