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

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

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

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

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

    //
    // 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 freeShouldHighlight = info[0] && info[0] === 'highlight';

    const freeRows = free.map((row, i) => {
        const cells = row.map((c, j) => {
            const highlighted = () => {
                if (!c || !freeShouldHighlight) return false;
                if (info[1] === 'skill') return j === 1;
                if (info[1] === 'spec') return j === 2;
                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={() => { if (c) return setInfo('item', c); }}
                onDblClick={() => sendVboxAccept(j, i) }
                >
                {convertVar(c)}
            </td>;
        });

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

    //
    //  INVENTORY
    //
    function boundClick(e, i, highlight) {
        if (reclaiming && vbox.bound[i]) sendVboxReclaim(i);
        else if (highlight && activeCryp) {
            sendVboxApply(i);
            showTeam();
        } else if (vbox.bound[i]) {
            const insert = combiner.findIndex(j => j === null);
            if (insert === -1) return setCombiner([i, null, null]);
            combiner[insert] = i;
            return setCombiner(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 = () => {
            if (!value || !info[0] || info[0] !== 'highlight') return false;
            const v = vboxInfo.vars.find(vi => vi.v === value);
            if (info[1] === 'skill') return v.skill;
            if (info[1] === 'spec') return v.spec;
            return false;
        };

        const highlight = highlighted();

        return (
            <td
                key={i}
                className={`${highlight ? 'highlight' : ''}`}
                onClick={e => boundClick(e, i, highlight) }>
                {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 setCombiner(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} 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>
            <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>
    );
}

module.exports = Vbox;
