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

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

function convertVar(v) {
    if (['Red', 'Green', 'Blue'].includes(v)) {
        return (
            shapes.vboxColour(v.toLowerCase())
        );
    }
    return v || <span>&nbsp;</span>;
    // uncomment for double borders in vbox;
    // if (v) {
    //     return <div>{v}</div>;
    // }
    // return;
}

function Vbox(args) {
    const {
        activeVar,
        activeCryp,
        player,
        // instance,
        combiner,
        reclaiming,
        sendVboxAccept,
        sendVboxDiscard,
        sendVboxReclaim,
        sendVboxCombine,
        setCombiner,
        setReclaiming,
        setActiveVar,
        setInfo,
    } = args;

    if (!player) 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 freeRows = free.map((row, i) => {
        const cells = row.map((c, j) => (
            <td
                key={j}
                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
    //

    let boundTimer;
    function boundTouchStart(e, i) {
        // e.preventDefault();
        // e.stopPropagation();
        boundTimer = (setTimeout(() => {
            boundTimer = null;
            return setActiveVar(i);
        }, LONG_TOUCH_TIME));
        return true;
    }

    function boundTouchEnd(e, i) {
        if (boundTimer) {
            clearTimeout(boundTimer);

            if (reclaiming && vbox.bound[i]) sendVboxReclaim(i);
            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 true;
    }

    function boundTouchMove(e) {
        if (boundTimer) clearTimeout(boundTimer);
        e.stopPropagation();
        return true;
    }

    function boundClick(e, i) {
        if (reclaiming && vbox.bound[i]) sendVboxReclaim(i);
        else if (vbox.bound[i]) {
            const insert = combiner.findIndex(j => j === null);
            if (insert === -1) return setCombiner([i, null, null]);
            combiner[insert] = i;
            boundTimer = null;
            return setCombiner(combiner);
        }
        return false;
    }

    const boundTds = range(0, 9).map(i => {
        if (combiner.indexOf(i) > -1) {
            return (
                <td
                    key={i}>
                    &nbsp;
                </td>
            );
        }
        return (
            <td
                key={i}
                draggable="true"
                onDragStart={e => e.dataTransfer.setData('text', i)}

                onTouchStart={e => boundTouchStart(e, i)}
                onTouchEnd={e => boundTouchEnd(e, i)}
                onTouchMove={e => boundTouchMove(e)}

                onClick={e => boundClick(e, i) }>
                {convertVar(vbox.bound[i])}
            </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)}>{convertVar(vbox.bound[combiner[0]])}</td>
                    <td onClick={() => combinerRmv(1)}>{convertVar(vbox.bound[combiner[1]])}</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 ${activeVar !== null || activeCryp ? '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;
