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

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

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

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

        return {
            instance,
            chatShow,
            account,
            tutorial,

            sendReady,
        };
    },

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

        return {
            setChatShow,
        };
    }
);

function InstanceCtrlBtns(args) {
    const {
        instance,
        chatShow,
        account,
        tutorial,
        sendReady,
        setChatShow,
    } = args;

    const finished = instance && instance.phase === 'Finished';
    const tutorialDisable = instance.time_control === 'Practice' && tutorial && tutorial < 8;
    return (
        <div class="instance-ctrl-btns">
            <button disabled={!account.subscribed} onClick={() => setChatShow(!chatShow)}>Chat</button>
            <button disabled={finished || tutorialDisable} class="ready" onClick={() => sendReady()}>Ready</button>
        </div>
    );
}

module.exports = addState(InstanceCtrlBtns);
