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

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

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

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

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

        function sendAbandon() {
            const id = instance ? instance.id : game.instance;
            return ws.sendInstanceAbandon(id);
        }

        return {
            game,
            instance,
            animating,

            sendAbandon,
            sendGameSkillClear,
        };
    },
);

function InstanceCtrlBtns(args) {
    const {
        sendAbandon,
        animating,
        sendGameSkillClear,

        game,
        instance,
    } = args;

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

    const { abandonState } = this.state;

    const cancelAbandon = e => {
        e.stopPropagation();
        return this.setState({ abandonState: false });
    };

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

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

    return (
        <div class="instance-ctrl-btns">
            {game ? <button disabled={animating} onClick={sendGameSkillClear}>Clear</button> : null}
            <button class={abandonClasses} disabled={animating || finished} onClick={abandonAction}>Abandon</button>
        </div>
    );
}

module.exports = addState(InstanceCtrlBtns);
