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

const { convertItem } = require('../utils');
const actions = require('../actions');

const addState = connect(
    function receiveState(state) {
        const {
            info, instance, itemInfo, tutorial, vboxInfo,
        } = state;
        return {
            info, instance, itemInfo, tutorial, vboxInfo,
        };
    },

    function receiveDispatch(dispatch) {
        function setComboPreview(item) {
            return dispatch(actions.setComboPreview(item));
        }

        return {
            setComboPreview,
        };
    }
);

class Combos extends preact.Component {
    shouldComponentUpdate(newProps) {
        if (newProps.info !== this.props.info) return true;
        if (newProps.instance !== this.props.instance) return true;
        if (newProps.itemInfo !== this.props.itemInfo) return true;
        if (newProps.tutorial !== this.props.tutorial) return true;
        if (newProps.vboxInfo !== this.props.vboxInfo) return true;
        return false;
    }

    render(props) {
        const {
            info,
            instance,
            itemInfo,
            tutorial,
            vboxInfo,
            setComboPreview,
        } = props;
        if (tutorial && instance.time_control === 'Practice' && instance.rounds.length === 1) return false;

        const vboxCombos = itemInfo.combos.filter(c => c.components.includes(vboxInfo || info));
        if (vboxCombos.length > 6 || vboxCombos.length === 0) return <div class="combos"></div>;

        const comboTable = vboxCombos.map((c, i) => {
            const mouseOver = e => {
                e.stopPropagation();
                setComboPreview(c.item);
            };
            const componentTable = (c.components.some(ci => ['Red', 'Blue', 'Green'].includes(ci)))
                ? [<div key="0">{convertItem(c.components[0])}&nbsp;{convertItem(c.components[1])}</div>,
                    <div key="1">{convertItem(c.components[2])}</div>]
                : c.components.map((u, j) => <div key={j} >{convertItem(u)}</div>);
            return (
                <div key={i} onMouseOver={mouseOver} class="table-button">
                    <div class="item">
                        {convertItem(c.item)}
                    </div>
                    {componentTable}
                </div>
            );
        });
        return (
            <div class="combos">
                <div class="combo-header">
                    <h2>COMBOS</h2>
                </div>
                <div class="combo-list"
                    onMouseOver={e => e.stopPropagation()}
                    onClick={e => e.stopPropagation()}>
                    {comboTable}
                </div>
            </div>
        );
    }
}

module.exports = addState(Combos);
