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

const Vbox = require('./vbox.component');
const InstanceConstructsContainer = require('./instance.constructs');
const Faceoff = require('./faceoff');

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

const addState = connect(
    function receiveState(state) {
        const {
            comboPreview,
            instance,
            nav,
        } = state;
        return {
            comboPreview,
            instance,
            nav,
        };
    },

    function receiveDispatch(dispatch) {
        function setInfo(c) {
            return dispatch(actions.setInfo(c));
        }


        function clearItems() {
            dispatch(actions.setItemUnequip([]));
            dispatch(actions.setVboxCombiner(null));
            dispatch(actions.setVboxHighlight(null));
            dispatch(actions.setVboxInfo(null));
            dispatch(actions.setVboxSelected({ storeSelect: [], stashSelect: [] }));
            return true;
        }

        function clearComboPreview() {
            return dispatch(actions.setComboPreview(null));
        }

        return {
            clearComboPreview,
            setInfo,
            clearItems,
        };
    }
);

function Instance(args) {
    const {
        comboPreview,
        instance,
        clearComboPreview,
        clearItems,
    } = args;

    if (!instance) return false;

    if (instance.phase !== 'InProgress') {
        return <Faceoff />;
    }

    function instanceClick(e) {
        e.stopPropagation();
        clearItems();
    }

    function mouseOver(e) {
        e.stopPropagation();
        if (comboPreview) clearComboPreview();
    }

    return (
        <main id="instance" class='instance' onClick={instanceClick} onMouseOver={mouseOver}>
            <Vbox />
            <InstanceConstructsContainer />
        </main>
    );
}

module.exports = addState(Instance);
