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

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

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

        function sendReady() {
            document.activeElement.blur();
            return ws.sendInstanceReady(instance.id);
        }

        function sendAbandon() {
            return ws.sendInstanceAbandon(instance.id);
        }

        return {
            instance,
            chatShow,
            account,

            sendAbandon,
            sendReady,
        };
    },

    function receiveDispatch(dispatch) {
        function setChatShow(v) {
            dispatch(actions.setChatShow(v));
        }

        return {
            setChatShow,
        };
    }
);

function InstanceCtrlBtns(args) {
    const {
        instance,
        chatShow,
        account,

        sendAbandon,
        sendReady,
        setChatShow,
    } = args;

    const finished = instance && instance.phase === 'Finished';

    // cheeky to make sure nubs don't just abandon their first game
    const beingNub = instance.phase_end
        && instance.phase === 'Lobby'
        && Date.parse(instance.phase_end) - Date.now() < 2000;

    if (beingNub) {
        sendReady();
    }

    return (
        <div class="instance-ctrl-btns">
            <button disabled={!account.subscribed} onClick={() => setChatShow(!chatShow)}>Chat</button>
            <button disabled={finished} class="ready" onClick={() => sendReady()}>Ready</button>
        </div>
    );
}

module.exports = addState(InstanceCtrlBtns);
