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

const addState = connect(({ vboxCombiner }) => ({ vboxCombiner }));

class Combiner extends preact.Component {
    shouldComponentUpdate(newProps) {
        if (newProps.vbox !== this.props.vbox) return true;
        if (newProps.vboxSelected !== this.props.vboxSelected) return true;
        if (newProps.vboxBuySelected !== this.props.vboxBuySelected) return true;
        if (newProps.sendVboxCombine !== this.props.sendVboxCombine) return true;
        if (newProps.vboxCombiner !== this.props.vboxCombiner) return true;
        return false;
    }

    render(args) {
        const {
            // passed props
            vbox,
            vboxSelected,
            vboxBuySelected,
            sendVboxCombine,
            // state props
            vboxCombiner,
        } = args;

        const { stashSelect, storeSelect } = vboxSelected;

        if (vboxCombiner) {
            const combinerComboText = vboxCombiner.replace('Plus', '+');
            let bits = 0;
            storeSelect.forEach(item => bits += item[0] + 1);
            return (
                <button
                    class='combiner vbox-btn'
                    disabled={bits > vbox.bits}
                    onClick={e => e.stopPropagation()}
                    onMouseDown={sendVboxCombine}>
                    {bits ? `Buy ${combinerComboText} ${bits}b` : `Combine ${combinerComboText}`}
                </button>
            );
        }

        if (stashSelect.length === 0 && storeSelect.length === 1) {
            const item = storeSelect[0];
            return (
                <button
                    class='combiner vbox-btn'
                    onClick={e => e.stopPropagation()}
                    onMouseDown={vboxBuySelected}>
                    {`Buy ${vbox.free[item[0]][item[1]]} ${item[0] + 1}b`}
                </button>
            );
        }

        return false;
    }
}

module.exports = addState(Combiner);
