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

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

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

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

        return {
            game,

            sendAbandon,
        };
    },
    function receiveDispatch(dispatch) {
        function leave() {
            dispatch(actions.setNav('play'));
            dispatch(actions.setGame(null));
            dispatch(actions.setInstance(null));
        }

        return { leave };
    }
);

function GameCtrlTopBtns(args) {
    const {
        game,

        leave,
        sendAbandon,
    } = args;

    const finished = game && game.phase === 'Finished';
    const { abandonState } = this.state;

    const abandonStateTrue = e => {
        e.stopPropagation();
        this.setState({ abandonState: true });
        setTimeout(() => this.setState({ abandonState: false }), 2000);
    };

    const abandonClasses = `abandon ${abandonState ? 'confirming' : ''}`;
    const abandonText = abandonState ? 'Confirm' : 'Abandon';
    const abandonAction = abandonState ? sendAbandon : abandonStateTrue;

    const abandonBtn = <button class={abandonClasses} disabled={finished} onClick={abandonAction}>{abandonText}</button>;
    const leaveBtn = <button class='abandon confirming' onClick={leave}>Leave</button>;

    return (
        <div class="instance-ctrl-btns">
            {finished ? leaveBtn : abandonBtn}
        </div>
    );
}

module.exports = addState(GameCtrlTopBtns);
