package doglet.misc;

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

import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * 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 xbarlib {

    private static final int MAX_DATA = 128;

    /******************************************************************/
    /* CPU Crossbar Class                                             */
    /******************************************************************/

    public final static class Crossbar {
        private final Semaphore head = new Semaphore(0);
        private final Semaphore tail = new Semaphore(1);
        private final int[] data = new int[1+MAX_DATA];
    }

    private static void cpu_data_store(int[] data, int[] src, int offset, int len) {
        data[0] = len;
        for (int i = 0; i < len; i++)
            data[1+i] = src[offset+i];
    }

    /**
     * cpu_data_load(src, dst, offset, len):
     * Unlike streams, this is an all or nothing load.
     * @return if != len nothing loaded, otherwise everything loaded.
     */
    private static int cpu_data_load(int[] src, int[] dst, int offset, int len) {
        int res = src[0];
        if (res != len)
            return res;
        for (int i = 0; i < len; i++)
            dst[offset + i] = src[1 + i];
        return len;
    }

    public static void cpu_xbar_put(Crossbar xbar, int[] src, int offset, int len)
            throws InterruptedException {
        xbar.tail.acquire();
        cpu_data_store(xbar.data, src, offset, len);
        xbar.head.release();
    }

    /**
     * cpu_xbar_take(xbar, dst, offset, len):
     * Unlike streams, this is an all or nothing take.
     * @return if != len nothing loaded, otherwise everything loaded.
     */
    public static int cpu_xbar_take(Crossbar xbar, int[] dst, int offset, int len)
            throws InterruptedException {
        xbar.head.acquire();
        int res = cpu_data_load(xbar.data, dst, offset, len);
        xbar.tail.release();
        return res;
    }

    public static boolean cpu_xbar_offer(Crossbar xbar, int[] src, int offset, int len) {
        if (!xbar.tail.tryAcquire())
            return false;
        cpu_data_store(xbar.data, src, offset, len);
        xbar.head.release();
        return true;
    }

    /**
     * cpu_xbar_poll(xbar, dst, offset, len):
     * Unlike streams, this is an all or nothing poll.
     * @return -1 if nothing available, otherwise all or nothing.
     */
    public static int cpu_xbar_poll(Crossbar xbar, int[] dst, int offset, int len) {
        if (!xbar.head.tryAcquire())
            return -1;
        int res = cpu_data_load(xbar.data, dst, offset, len);
        xbar.tail.release();
        return res;
    }

    /******************************************************************/
    /* CPU Integer Arrays                                             */
    /******************************************************************/

    /**
     * test_cpu_buf_new(D, H): internal only
     * The predicate succeeds in H with the buffer from the list D.
     */
    private static boolean test_cpu_buf_new(Object[] args) {
        Object alpha = Machine.exec_build(args[0]);
        int[] res = cpu_list_ints(alpha);
        return Machine.exec_unify(args[1], res);
    }

    public static int[] cpu_list_ints(Object obj) {
        Object peek = obj;
        int i = 0;
        while (Store.is_structure(peek) &&
                ".".equals(((Store.Structure) peek).functor) &&
                ((Store.Structure) peek).args.length == 2 &&
                i < special.MAX_ARITY) {
            i++;
            peek = Store.deref(((Store.Structure) peek).args[1]);
        }
        special.check_nil(peek);
        int[] args = new int[i];
        peek = obj;
        i = 0;
        while (Store.is_structure(peek) &&
                ".".equals(((Store.Structure) peek).functor) &&
                ((Store.Structure) peek).args.length == 2) {
            Object val = Store.deref(((Store.Structure) peek).args[0]);
            special.check_integer(val);
            args[i++] = ((Number)val).intValue();
            peek = Store.deref(((Store.Structure) peek).args[1]);
        }
        return args;
    }

    /**
     * test_cpu_buf_current(H, D): internal only
     * The predicate succeeds in D with the list from the buffer H.
     */
    private static boolean test_cpu_buf_current(Object[] args) {
        int[] alpha = (int[])Machine.exec_build(args[0]);
        Object res = cpu_ints_list(alpha, 0, alpha.length);
        return Machine.exec_unify(args[1], res);
    }

    public static Object cpu_ints_list(int[] alpha, int off, int count) {
        Object res = "[]";
        for (int i = off + count - 1; i >= off; i--)
            res = new Store.Compound(".", new Object[]{Integer.valueOf(alpha[i]), res});
        return res;
    }

    /******************************************************************/
    /* CPU Crossbar Interface                                          */
    /******************************************************************/

    /**
     * test_cpu_xbar_new(A): internal only
     * The predicate succeeds in A with a new xbar.
     */
    private static boolean test_cpu_xbar_new(Object[] args) {
        Crossbar res = new Crossbar();
        return Machine.exec_unify(args[0], res);
    }

    /**
     * test_cpu_xbar_put(C, H, P): internal only
     * The predicate succeeds in P with a promise that
     * sends the buffer H to the xbar C.
     */
    private static boolean test_cpu_xbar_put(Object[] args) {
        Object xbar = Machine.exec_build(args[0]);
        check_xbar(xbar);
        int[] data = (int[])Machine.exec_build(args[1]);
        return Machine.exec_unify(args[2],
                cpu_put_promise(Machine.engine, (Crossbar)xbar, data));
    }

    private static Handler.Promise cpu_put_promise(Machine.Engine en, Crossbar xbar, int[] data) {
        return new Handler.Promise(() -> {
            Thread self = Thread.currentThread();
            en.abort = self::interrupt;
            try {
                cpu_xbar_put(xbar, data, 0, data.length);
            } catch (InterruptedException x) {
                /* */
            } finally {
                en.abort = () -> {};
            }
        });
    }

    /**
     * test_cpu_xbar_take(C, M, P): internal only
     * The predicate succeeds in P with a promise that
     * receives a buffer into the map M from the xbar C.
     */
    private static boolean test_cpu_xbar_take(Object[] args) {
        Object xbar = Machine.exec_build(args[0]);
        check_xbar(xbar);
        Map map = (Map)Machine.exec_build(args[1]);
        return Machine.exec_unify(args[2],
                cpu_take_promise(Machine.engine, (Crossbar)xbar, map));
    }

    private static Handler.Promise cpu_take_promise(Machine.Engine en, Crossbar xbar, Map map) {
        return new Handler.Promise(() -> {
            Thread self = Thread.currentThread();
            en.abort = self::interrupt;
            try {
                int len = ((Number)map.get("len")).intValue();
                int[] data = new int[len];
                int res = cpu_xbar_take(xbar, data, 0, len);
                if (res != len) {
                    map.put("len", Integer.valueOf(res));
                } else {
                    map.put("data", data);
                }
            } catch (InterruptedException x) {
                /* */
            } finally {
                en.abort = () -> {};
            }
        });
    }

    /**
     * test_cpu_xbar_offer(C, H): internal only
     * The predicate succeeds when it can send
     * the buffer H to the xbar C.
     */
    private static boolean test_cpu_xbar_offer(Object[] args) {
        Object xbar = Machine.exec_build(args[0]);
        check_xbar(xbar);
        int[] data = (int[])Machine.exec_build(args[1]);
        return cpu_xbar_offer((Crossbar)xbar, data, 0, data.length);
    }

    /**
     * test_cpu_xbar_poll(C, M): internal only
     * The predicate succeeds with it can receives
     * a buffer into the map M from the xbar C.
     */
    private static boolean test_cpu_xbar_poll(Object[] args) {
        Object xbar = Machine.exec_build(args[0]);
        check_xbar(xbar);
        Map map = (Map)Machine.exec_build(args[1]);
        int len = ((Number)map.get("len")).intValue();
        int[] data = new int[len];
        int res = cpu_xbar_poll((Crossbar)xbar, data, 0, len);
        if (res == -1)
            return false;
        if (res != len) {
            map.put("len", Integer.valueOf(res));
        } else {
            map.put("data", data);
        }
        return true;
    }

    /******************************************************************/
    /* CPU Crossbar Arrays                                             */
    /******************************************************************/

    /**
     * test_cpu_comm_new(D, H): internal only
     * The predicate succeeds in H with the table from the list D.
     */
    private static boolean test_cpu_comm_new(Object[] args) {
        Object alpha = Machine.exec_build(args[0]);
        Crossbar[] res = cpu_list_comm(alpha);
        return Machine.exec_unify(args[1], res);
    }

    public static Crossbar[] cpu_list_comm(Object obj) {
        Object peek = obj;
        int i = 0;
        while (Store.is_structure(peek) &&
                ".".equals(((Store.Structure) peek).functor) &&
                ((Store.Structure) peek).args.length == 2 &&
                i < special.MAX_ARITY) {
            i++;
            peek = Store.deref(((Store.Structure) peek).args[1]);
        }
        special.check_nil(peek);
        Crossbar[] args = new Crossbar[i];
        peek = obj;
        i = 0;
        while (Store.is_structure(peek) &&
                ".".equals(((Store.Structure) peek).functor) &&
                ((Store.Structure) peek).args.length == 2) {
            Object val = Store.deref(((Store.Structure) peek).args[0]);
            check_xbar(val);
            args[i++] = (Crossbar)val;
            peek = Store.deref(((Store.Structure) peek).args[1]);
        }
        return args;
    }

    private static void check_xbar(Object beta) {
        if (!(beta instanceof Crossbar)) {
            Store.check_nonvar(beta);
            beta = Store.copy_term(beta);
            throw Machine.make_error(new Store.Compound("type_error",
                    new Object[]{"xbar", beta}));
        }
    }

    /******************************************************************/
    /* Chan Lib Init                                                  */
    /******************************************************************/

    public static void main() {
        Store.set("cpu_buf_new", 2, special.make_check(xbarlib::test_cpu_buf_new));
        Store.set("cpu_buf_current", 2, special.make_check(xbarlib::test_cpu_buf_current));
        Store.set("cpu_xbar_new", 1, special.make_check(xbarlib::test_cpu_xbar_new));
        Store.set("cpu_xbar_put", 3, special.make_check(xbarlib::test_cpu_xbar_put));
        Store.set("cpu_xbar_take", 3, special.make_check(xbarlib::test_cpu_xbar_take));
        Store.set("cpu_xbar_offer", 2, special.make_check(xbarlib::test_cpu_xbar_offer));
        Store.set("cpu_xbar_poll", 2, special.make_check(xbarlib::test_cpu_xbar_poll));
        Store.set("cpu_comm_new", 2, special.make_check(xbarlib::test_cpu_comm_new));
    }

}
