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

const Vbox = require('./vbox.component');
const InfoContainer = require('./info.container');
const InstanceCrypsContainer = require('./instance.cryps');
const EquipmentContainer = require('./instance.equip');

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

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

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

        return { instance, player, sendInstanceReady };
    },

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

        return {
            setInfo,
        };
    }
);

function Instance(args) {
    const {
        instance,
        player,
        sendInstanceReady,
        setInfo,
    } = args;

    if (!instance) return false;

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

    const rdyClasses = `instance-btn instance-ui-btn ${player.ready ? 'ready' : ''}`;
    const readyBtn = (
        <button
            className={rdyClasses}
            onMouseOver={e => hoverInfo(e, 'ready')}
            onClick={() => sendInstanceReady()}>
            Ready
        </button>
    );

    const actionBtn = player
        ? readyBtn
        : null;

    // TIMER
    const zero = Date.parse(instance.phase_end) - (1000 * 120);
    const now = Date.now();
    const end = Date.parse(instance.phase_end);
    const timerPct = ((now - zero) / (end - zero) * 100);
    const timerStyles = {
        width: `${timerPct < 100 ? timerPct : 0}%`,
        background: player.ready ? 'forestgreen' : 'whitesmoke',
    };

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

    return (
        <main className="instance" onMouseOver={() => setInfo(null)} >
            <div className="top">
                {actionBtn}
                {timer}
            </div>

            <input type="checkbox" id="toggle-vbox"/>
            <label id="toggle-vbox-label" htmlFor="toggle-vbox">&nbsp;</label>
            <Vbox />
            <InfoContainer />
            <EquipmentContainer />
            <InstanceCrypsContainer />
        </main>
    );
}

module.exports = addState(Instance);
