package doglet.misc;

import nova.Handler;
import nova.Machine;
import nova.Store;
import nova.special;

/**
 * Warranty & Liability
 * To the extent permitted by applicable law and unless explicitly
 * otherwise agreed upon, XLOG Technologies AG makes no warranties
 * regarding the provided information. XLOG Technologies AG assumes
 * no liability that any problems might be solved with the information
 * provided by XLOG Technologies AG.
 *
 * Rights & License
 * All industrial property rights regarding the information - copyright
 * and patent rights in particular - are the sole property of XLOG
 * Technologies AG. If the company was not the originator of some
 * excerpts, XLOG Technologies AG has at least obtained the right to
 * reproduce, change and translate the information.
 *
 * Reproduction is restricted to the whole unaltered document. Reproduction
 * of the information is only allowed for non-commercial uses. Selling,
 * giving away or letting of the execution of the library is prohibited.
 * The library can be distributed as part of your applications and libraries
 * for execution provided this comment remains unchanged.
 *
 * Restrictions
 * Only to be distributed with programs that add significant and primary
 * functionality to the library. Not to be distributed with additional
 * software intended to replace any components of the library.
 *
 * Trademarks
 * Jekejeke is a registered trademark of XLOG Technologies AG.
 */

public final class hacklib {
    private static final int MAX_TILT = 64;
    private static final int GROUP_SIZE = 8;
    
    private static final class CpuMap {
        private int[] code;
        private int[] offset;
        private xbarlib.Crossbar[] comm;
        private int[] state;
    }

    private static final class CpuWarp {
        private CpuMap map;
        private int from;
        private int to;
        private Thread thread;
    }

    private static void run(CpuWarp warp) {
        CpuMap pi = warp.map;
        for (int i = warp.from; i < warp.to; i++)
            pi.state[pi.offset[i]-3] = i;
        boolean active = true;
        while (active) {
            active = false;
            for (int i = warp.from; i < warp.to; i++) {
                if (run_id(pi, i))
                    active = true;
            }
        }
    }

    private static boolean run_id(CpuMap pi, int id) {
        int base = pi.offset[id];
        int pc = pi.state[base-2];
        int accu = pi.state[base-1];
        for (int k = 0; k < MAX_TILT; k++) {
            if (pc < pi.code.length) {
                int instr = pi.code[pc];
                int value = hack_get(pi, instr, pc, base);
                pc = hack_set(pi, instr, accu, pc, base);
                accu = hack_fun(instr, accu, value);
            } else {
                pi.state[base-2] = pc;
                pi.state[base-1] = accu;
                return false;
            }
        }
        pi.state[base-2] = pc;
        pi.state[base-1] = accu;
        return true;
    }

    private static int hack_get(CpuMap pi, int instr, int pc, int base) {
        switch ((instr>>28) & 0x0F) {
            case 0: /* cst */
                int cst = (instr & 0x00FFFFFF) - 0x00800000;
                return cst;
            case 1: /* get */
                int get = (instr & 0x00FFFFFF) - 0x00800000;
                return pi.state[base+get];
            case 2: /* ext */
                return pi.code[pc+1];
            case 3: /* out */
                int out = (instr & 0x00FFFFFF) - 0x00800000;
                return extra_output(pi, out, base);
            case 4: /* in */
                int in = (instr & 0x00FFFFFF) - 0x00800000;
                return extra_input(pi, in, base);
            case 5: /* set */
                return 0;
            case 6: /* bra */
                return pc+1;
            case 7: /* brz */
                return pc+1;
            case 8: /* jma */
                return pc+1;
            case 9: /* jmz */
                return pc+1;
            default:
                throw new IllegalArgumentException("illegal mode");
        }
    }

    private static int hack_set(CpuMap pi, int instr, int accu, int pc, int base) {
        switch ((instr>>28) & 0x0F) {
            case 0: /* get */
                return pc+1;
            case 1: /* cst */
                return pc+1;
            case 2: /* ext */
                return pc+2;
            case 3: /* out */
                return pc+1;
            case 4: /* in */
                return pc+1;
            case 5: /* set */
                int set = (instr & 0x00FFFFFF) - 0x00800000;
                pi.state[base+set] = accu;
                return pc+1;
            case 6: /* bra */
                int bra = (instr & 0x00FFFFFF) - 0x00800000;
                return bra;
            case 7: /* brz */
                int brz = (instr & 0x00FFFFFF) - 0x00800000;
                return (accu == 0 ? brz : pc+1);
            case 8: /* jma */
                int jma = (instr & 0x00FFFFFF) - 0x00800000;
                return pi.state[base+jma];
            case 9: /* jmz */
                int jmz = (instr & 0x00FFFFFF) - 0x00800000;
                return (accu == 0 ? pi.state[base+jmz] : pc+1);
            default:
                throw new IllegalArgumentException("illegal mode");
        }
    }

    private static int hack_fun(int instr, int accu, int value) {
        switch ((instr>>24) & 0x0F) {
            case 0: /* mov */
                return value;
            case 1: /* neg */
                return -value;
            case 2: /* add */
                return accu + value;
            case 3: /* sub */
                return accu - value;
            case 4: /* mul */
                return accu * value;
            case 5: /* zdiv */
                return accu / value;
            case 6: /* rem */
                return accu % value;
            case 7: /* min */
                return Math.min(accu, value);
            case 8: /* max */
                return Math.max(accu, value);
            case 9: /* eq */
                return (accu == value ? 1 : 0);
            case 10: /* nq */
                return (accu != value ? 1 : 0);
            case 11: /* ls */
                return (accu < value ? 1 : 0);
            case 12: /* gr */
                return (accu > value ? 1 : 0);
            case 13: /* lq */
                return (accu <= value ? 1 : 0);
            case 14: /* gq */
                return (accu >= value ? 1 : 0);
            default:
                throw new IllegalArgumentException("illegal fun");
        }
    }

    /******************************************************************/
    /* Hack Output/Input                                              */
    /******************************************************************/

    private static int extra_output(CpuMap pi, int obj, int base) {
        xbarlib.Crossbar chan = pi.comm[obj];
        return (xbarlib.cpu_xbar_offer(chan, pi.state, base+1, pi.state[base]) ? 1 : 0);
    }

    private static int extra_input(CpuMap pi, int obj, int base) {
        xbarlib.Crossbar chan = pi.comm[obj];
        int len = pi.state[base];
        int res = xbarlib.cpu_xbar_poll(chan, pi.state, base+1, len);
        if (res == -1)
            return 0;
        if (res != len)
            pi.state[base] = res;
        return 1;
    }

    /******************************************************************/
    /* Hack Constructor                                               */
    /******************************************************************/

    /**
     * test_cpu_comp_new(C, O, T, S, M): internal only
     * The predicate succeeds in M with a new CPU backed π-WAM for
     * the code buffer C, the offsets buffer O, the channel table T
     * and the state buffer S.
     */
    private static boolean test_cpu_comp_new(Object[] args) {
        CpuMap res = new CpuMap();
        res.code = (int[])Machine.exec_build(args[0]);
        res.offset = (int[])Machine.exec_build(args[1]);
        res.comm = (xbarlib.Crossbar[])Machine.exec_build(args[2]);
        res.state = (int[])Machine.exec_build(args[3]);
        return Machine.exec_unify(args[4], res);
    }

    /**
     * test_cpu_comp_count(M, C): internal only
     * The predicate succeeds in C with the current
     * number of groups in the CPU backed π-WAM M.
     */
    private static boolean test_cpu_comp_count(Object[] args) {
        CpuMap alpha = (CpuMap)Machine.exec_build(args[0]);
        int res = alpha.offset.length;
        res = (res+GROUP_SIZE-1)/GROUP_SIZE;
        return Machine.exec_unify(args[1], Integer.valueOf(res));
    }

    /******************************************************************/
    /* Hack Interface                                                */
    /******************************************************************/

    /**
     * test_cpu_group_new(M, G): internal only
     * The predicate succeeds in G with a
     * new group for the CPU backed π-WAM M.
     */
    private static boolean test_cpu_group_new(Object[] args) {
        CpuMap alpha = (CpuMap)Machine.exec_build(args[0]);
        CpuWarp res = new CpuWarp();
        res.map = alpha;
        res.thread = new Thread(() -> run(res));
        return Machine.exec_unify(args[1], res);
    }

    /**
     * test_cpu_group_start(G, I): internal only
     * The predicate succeeds. As a side effect it
     * starts the group G at group index I.
     */
    private static boolean test_cpu_group_start(Object[] args) {
        CpuWarp alpha = (CpuWarp)Machine.exec_build(args[0]);
        Number beta = (Number)Machine.exec_build(args[1]);
        int at = beta.intValue()*GROUP_SIZE;
        int len = Math.min(alpha.map.offset.length - at, GROUP_SIZE);
        alpha.from = at;
        alpha.to = at+len;
        alpha.thread.start();
        return true;
    }

    /**
     * test_cpu_group_join(G, P): internal only
     * The predicate succeeds in P with a new promise
     * that waits for the group G to finish.
     */
    private static boolean test_cpu_group_join(Object[] args) {
        CpuWarp alpha = (CpuWarp)Machine.exec_build(args[0]);
        return Machine.exec_unify(args[1],
                cpu_join_promise(Machine.engine, alpha.thread));
    }

    private static Handler.Promise cpu_join_promise(Machine.Engine en, Thread alpha) {
        return new Handler.Promise(() -> {
            Thread self = Thread.currentThread();
            en.abort = self::interrupt;
            try {
                alpha.join();
            } catch (InterruptedException x) {
                /* */
            } finally {
                en.abort = () -> {};
            }
        });
    }

    /**
     * test_cpu_group_free(G): internal only
     * The predicate succeeds. As a side effect
     * it frees the group G.
     */
    private static boolean test_cpu_group_free(Object[] args) {
        return true;
    }

    /******************************************************************/
    /* Hack Lib Init                                                  */
    /******************************************************************/

    public static void main() {
        Store.set("cpu_comp_new", 5, special.make_check(hacklib::test_cpu_comp_new));
        Store.set("cpu_comp_count", 2, special.make_check(hacklib::test_cpu_comp_count));
        Store.set("cpu_group_new", 2, special.make_check(hacklib::test_cpu_group_new));
        Store.set("cpu_group_start", 2, special.make_check(hacklib::test_cpu_group_start));
        Store.set("cpu_group_join", 2, special.make_check(hacklib::test_cpu_group_join));
        Store.set("cpu_group_free", 1, special.make_check(hacklib::test_cpu_group_free));
    }

}
