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);
        }

        return {
            instance,
            chatShow,
            account,

            sendReady,
        };
    },

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

        return {
            setChatShow,
        };
    }
);

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

        sendReady,
        setChatShow,
    } = args;

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

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