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

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

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

        function sendReady() {
            document.activeElement.blur();
            return ws.sendGameReady(game.id);
        }

        function getInstanceState() {
            return ws.sendInstanceState(game.instance);
        }

        function sendGameSkillClear() {
            return ws.sendGameSkillClear(game.id);
        }

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

        return {
            game,
            account,
            chatShow,
            sendAbandon,
            sendGameSkillClear,
            sendReady,
            getInstanceState,
            animating,
        };
    },

    function receiveDispatch(dispatch) {
        function quit() {
            dispatch(actions.setNav('transition'));
            dispatch(actions.setGame(null));
        }

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

        return {
            setChatShow,
            quit,
        };
    }
);

function GameCtrlBtns(args) {
    const {
        game,
        animating,
        account,
        chatShow,

        getInstanceState,
        sendGameSkillClear,
        sendReady,
        setChatShow,
        quit,
    } = args;

    if (!game) return false;
    const finished = game.phase === 'Finished';

    function quitClick() {
        getInstanceState();
        quit();
    }

    const readyBtn = <button disabled={animating} class="ready" onClick={() => sendReady()}>Ready</button>;
    const quitBtn = <button disabled={animating} class="quit" onClick={quitClick}>Back</button>;

    return (
        <div class="game-ctrl-btns">
            <button disabled={!account.subscribed} onClick={() => setChatShow(!chatShow)}>Chat</button>
            <button disabled={animating} onClick={sendGameSkillClear}>Clear</button>
            {finished ? quitBtn : readyBtn}
        </div>
    );
}

module.exports = addState(GameCtrlBtns);
