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

const actions = require('./../actions');
const { COLOURS } = require('./../utils');
const { ConstructAvatar } = require('./construct');

const addState = connect(
    function receiveState(state) {
        const { ws, constructs, teamPage, teamSelect } = state;

        function sendConstructSpawn(name) {
            return ws.sendMtxConstructSpawn(name);
        }

        return {
            constructs,
            teamPage,
            teamSelect,
        };
    },
    function receiveDispatch(dispatch) {
        function setTeam(constructIds) {
            dispatch(actions.setTeamSelect(constructIds));
        }

        return {
            setTeam,
        };
    }
);

function Collection(args) {
    const {
        constructs,
        teamPage,
        teamSelect,
        setTeam,
    } = args;

    if (!constructs) return <div></div>;

    // redux limitation + suggested workaround
    // so much for dumb components
    function selectConstruct(id) {
        // remove
        const i = teamSelect.findIndex(sid => sid === id);
        if (i > -1) {
            teamSelect[i] = null;
            return setTeam(teamSelect);
        }

        // window insert
        const insert = teamSelect.findIndex(j => j === null);
        if (insert === -1) return setTeam([id, null, null]);
        teamSelect[insert] = id;
        return setTeam(teamSelect);
    }

    const dispConstructs = constructs.length >= ((teamPage + 1) * 6)
        ? constructs.slice(teamPage * 6, (teamPage + 1) * 6)
        : constructs.slice(teamPage * 6, constructs.length);

    const constructPanels = dispConstructs.map(construct => {
        const colour = teamSelect.indexOf(construct.id);
        const selected = colour > -1;

        const borderColour = selected ? COLOURS[colour] : '#000000';

        return (
            <div
                key={construct.id}
                class="construct team-select"
                style={ { 'border-color': borderColour || 'whitesmoke' } }
                onClick={() => selectConstruct(construct.id)} >
                <ConstructAvatar construct={construct} />
                <h2>{construct.name}</h2>
            </div>
        );
    });

    return (
        <section class="team">
            {constructPanels}
        </section>
    );
}

module.exports = addState(Collection);
