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

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

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

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

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

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

        function setInfo(c) {
            return dispatch(actions.setInfo(c));
        }

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

        return {
            setInfo,
            setNav,
            setShowNav,
        };
    }
);

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

        setInfo,
        setNav,
        setShowNav,

        sendInstanceReady,
    } = args;

    if (!instance || !player) {
        return (
            <footer id="footer">
                <button id="nav-btn" onClick={() => setShowNav(!showNav)} >☰</button>
            </footer>
        );
    }

    function hoverInfo(e, info) {
        e.stopPropagation();
        return setInfo(info);
    }

    const rdyClasses = `${player.ready ? 'ready ready-btn' : 'ready-btn'}`;
    const readyInfo = instance.phase === 'Lobby'
        ? 'lobbyReady'
        : 'ready';

    const readyBtn = (
        <button
            class={rdyClasses}
            onMouseOver={e => hoverInfo(e, readyInfo)}
            onClick={() => sendInstanceReady()}>
            Ready
        </button>
    );

    function navClick() {
        if (nav === 'vbox') return setNav('constructs');
        return setNav('vbox');
    }

    const navBtn = instance.phase === 'InProgress'
        ? (
            <button
                id="instance-nav"
                onClick={navClick}>
                {nav === 'vbox' ? 'Constructs' : 'Vbox'}
            </button>
        )
        : null;

    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}
            <button id="nav-btn" onClick={() => setShowNav(!showNav)} >☰</button>
            {navBtn}
            {readyBtn}
        </footer>
    );
}

module.exports = addState(Instance);
