const preact = require('preact');
const range = require('lodash/range');

const { stringSort } = require('./../utils');
const molecule = require('./molecule');
const SpawnButton = require('./spawn.button');

const idSort = stringSort('id');

const COLOURS = [
    '#a52a2a',
    '#1FF01F',
    '#3498db',
];

function CrypList(args) {
    const {
        cryps,
        selectedCryps,
        setSelectedCryps,
        sendPlayerMmCrypsSet,
        sendInstanceJoin,
        sendCrypSpawn
    } = args;

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

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

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

    const instanceJoinHidden = !selectedCryps.every(c => !!c);

    const mmSet = (
        <button
            className={`menu-instance-btn full left ${instanceJoinHidden ? 'hidden' : ''}`}
            disabled={instanceJoinHidden}
            onClick={() => sendPlayerMmCrypsSet()}>
            Set Matchmaking Team
        </button>
    );
    const instanceJoin = (
        <button
            className={`menu-instance-btn full right ${instanceJoinHidden ? 'hidden' : ''}`}
            disabled={instanceJoinHidden}
            onClick={() => sendInstanceJoin()}>
            Join New Instance
        </button>
    );


    const crypPanels = cryps.sort(idSort).map(cryp => {
        const colour = selectedCryps.indexOf(cryp.id);
        const selected = colour > -1;

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

        return (
            <div
                key={cryp.id}
                className="menu-cryp-ctr">
                <div
                    className="menu-cryp"
                    style={ { 'border-color': borderColour || 'whitesmoke' } }
                    onClick={() => selectCryp(cryp.id)} >
                    <figure className="img">
                        {molecule}
                    </figure>
                    <h2>{cryp.name}</h2>
                </div>
            </div>
        );
    });

    const spawnButtonsNum = cryps.length < 3
        ? (3 - cryps.length)
        : 1;

    const spawnButtons = range(spawnButtonsNum)
        .map(i => <SpawnButton key={i} i={i} spawn={name => sendCrypSpawn(name)} />);

    return (
        <div className="menu-cryps">
            {mmSet}
            {instanceJoin}
            {crypPanels}
            {spawnButtons}
        </div>
    );
}

module.exports = CrypList;
