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

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

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

function Vbox(args) {
    const {
        activeCryp,
        setActiveCryp,
        combiner,
        info,
        instance,
        player,
        reclaiming,
        sendVboxAccept,
        sendVboxApply,
        sendVboxCombine,
        sendVboxDiscard,
        sendVboxReclaim,
        setCombiner,
        setInfo,
        setReclaiming,
        showTeam,
        vboxHidden,
        vboxHighlight,
        setVboxHighlight,
        vboxInfo,
    } = args;

    if (!player) return false;
    if (instance.phase === 'Lobby') return false;
    const { vbox } = player;

    function combinerChange(newCombiner) {
        setCombiner(newCombiner);
        if (newCombiner.every(c => c === null)) return setVboxHighlight([]);

        const combinerValues = newCombiner.map(cv => player.vbox.bound[cv]).filter(cv => cv);

        const filteredCombos = vboxInfo.combos
            .filter(combo => combinerValues.every(u => combo.units.includes(u)));

        const comboValues = vboxInfo.vars.filter(v => {
            if (!filteredCombos.some(c => c.units.includes(v.v))) return false;
            if (!['Red', 'Green', 'Blue'].includes(v.v) && combinerValues.includes(v.v)) return false;
            return true;
        });

        return setVboxHighlight(comboValues.map(v => v.v));
    }

    //
    // VBOX
    //
    const free = [];
    for (let i = 0; i < 6; i++) {
        free.push([vbox.free[0][i], vbox.free[1][i], vbox.free[2][i]]);
    }

    let vboxTimer;
    const LONG_TOUCH_TIME = 500;
    function vboxTouchStart(e, i, j) {
        vboxTimer = (setTimeout(() => {
            sendVboxAccept(j, i);
            vboxTimer = null;
        }, LONG_TOUCH_TIME));
        return true;
    }

    function vboxTouchEnd(e, i, j) {
        if (vboxTimer) {
            clearTimeout(vboxTimer);
        }
        return true;
    }

    function vboxTouchMove(e) {
        if (vboxTimer) clearTimeout(vboxTimer);
        e.stopPropagation();
        return true;
    }

    const freeRows = free.map((row, i) => {
        const cells = row.map((c, j) => {
            const highlighted = c && vboxHighlight.includes(c);

            function freeClick() {
                if (c) {
                    setActiveCryp(null);
                    return setInfo('item', c);
                }
                return false;
            }

            return <td
                key={j}
                className={`${highlighted ? 'highlight' : ''}`}
                onTouchStart={e => vboxTouchStart(e, i, j)}
                onTouchEnd={e => vboxTouchEnd(e, i, j)}
                onTouchMove={e => vboxTouchMove(e)}

                onClick={freeClick}
                onDblClick={() => sendVboxAccept(j, i) }
                >
                {convertVar(c)}
            </td>;
        });

        return (
            <tr key={i}>
                {cells}
            </tr>
        );
    });

    //
    //  INVENTORY
    //
    function boundClick(e, i, highlight) {
        const value = vbox.bound[i];
        if (reclaiming && value) sendVboxReclaim(i);
        else if (highlight && activeCryp) {
            sendVboxApply(i);
            setVboxHighlight([]);
            showTeam();
        } else if (value) {
            const insert = combiner.findIndex(j => j === null);
            if (insert === -1) return combinerChange([i, null, null]);
            combiner[insert] = i;
            setInfo('item', value);
            setActiveCryp(null);
            return combinerChange(combiner);
        }
        return false;
    }

    const boundTds = range(0, 9).map(i => {
        const value = vbox.bound[i];
        if (combiner.indexOf(i) > -1) {
            return (
                <td
                    key={i}>
                    &nbsp;
                </td>
            );
        }

        const highlighted = value && vboxHighlight.includes(value);

        return (
            <td
                key={i}
                className={`${highlighted ? 'highlight' : ''}`}
                onClick={e => boundClick(e, i, highlighted) }>
                {convertVar(value)}
            </td>
        );
    });

    const boundRows = [
        <tr key={0} >
            {boundTds[0]}
            {boundTds[1]}
            {boundTds[2]}
        </tr>,
        <tr key={1}>
            {boundTds[3]}
            {boundTds[4]}
            {boundTds[5]}
        </tr>,
        <tr key={2}>
            {boundTds[6]}
            {boundTds[7]}
            {boundTds[8]}
        </tr>,
    ];

    //
    // COMBINER
    //
    function combinerRmv(i) {
        combiner[i] = null;
        return combinerChange(combiner);
    }
    const combinerElement = (
        <table className="vbox-table">
            <tbody>
                <tr>
                    <td onClick={() => combinerRmv(0)}>
                        {combiner[0] !== null ? convertVar(vbox.bound[combiner[0]]) : shapes.vboxColour('gray')}
                    </td>
                    <td onClick={() => combinerRmv(1)}>
                        {combiner[1] !== null ? convertVar(vbox.bound[combiner[1]]) : shapes.vboxColour('gray')}
                    </td>
                    <td onClick={() => combinerRmv(2)}>
                        {convertVar(vbox.bound[combiner[2]])}
                    </td>
                </tr>
            </tbody>
        </table>
    );

    //
    // EVERYTHING
    //

    function reclaimClick(e) {
        e.stopPropagation();
        return setReclaiming(!reclaiming);
    }

    const classes = `vbox ${vboxHidden ? 'hidden' : ''}`;
    const reclaimClass = `instance-btn instance-ui-btn vbox-btn ${reclaiming ? 'reclaiming' : ''}`;

    return (
        <div className={classes}>
            <div className='vbox-box' onClick={() => setReclaiming(false)} >
                <div className="vbox-hdr">
                    <div onTouchStart={e => e.target.scrollIntoView(true)}>VBOX</div>
                    <div className="bits" >{vbox.bits}b</div>
                </div>
                <button
                    className="instance-btn instance-ui-btn vbox-btn"
                    onClick={() => sendVboxDiscard()}>
                    Reroll
                </button>
                <table className="vbox-table">
                    <tbody>
                        {freeRows}
                    </tbody>
                </table>
            </div>
            <div className='vbox-inventory' onClick={() => setReclaiming(false)} >
                <span onTouchStart={e => e.target.scrollIntoView(true)}>INVENTORY</span>
                <button
                    className={reclaimClass}
                    onClick={reclaimClick}>
                    reclaim
                </button>
                <table className="vbox-table">
                    <tbody>
                        {boundRows}
                    </tbody>
                </table>
                <span onTouchStart={e => e.target.scrollIntoView(true)}>I-COMBINATOR</span>
                <button
                    className="instance-btn instance-ui-btn vbox-btn"
                    onClick={() => sendVboxCombine()}>
                    refine
                </button>
                {combinerElement}
            </div>
        </div>
    );
}

module.exports = Vbox;
