package doglet.util;

import nova.*;

import java.util.ArrayList;
import java.util.Map;

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

    /******************************************************************/
    /* ir_quote_new/2 and ir_quote_current/2                          */
    /******************************************************************/

    /**
     * test_ir_quote_new(D, H): internal only
     * The predicate succeeds in H with the quote from the term D.
     */
    private static boolean test_ir_quote_new(Object[] args) {
        Object alpha = Machine.exec_build(args[0]);
        alpha = special.freeze_quote(alpha);
        return Machine.exec_unify(args[1], alpha);
    }

    /**
     * special_ir_quote_current(H, D): internal only
     * The predicate succeeds in D with the term from the quote H.
     */
    private static Object special_ir_quote_current(Object[] args) {
        Object alpha = Store.deref(args[0]);
        alpha = Machine.melt_quote(alpha);
        if (!Machine.unify(args[1], alpha))
            return Boolean.FALSE;
        Machine.cont(((Store.Structure) Machine.call).args[1]);
        return Boolean.TRUE;
    }

    /******************************************************************/
    /* Semaphore                                                      */
    /******************************************************************/

    public static class Semaphore {
        int permits;

        /**
         * Create a semaphore.
         *
         * @param permits The initial number of permits.
         */
        public Semaphore(int permits) {
            this.permits = permits;
        }

    }

    public static void sem_release(Semaphore sem) {
        synchronized (sem) {
            sem.permits++;
            sem.notify();
        }
    }

    public static void sem_acquire(Semaphore sem)
            throws InterruptedException {
        synchronized (sem) {
            while (sem.permits == 0)
                sem.wait();
            sem.permits--;
        }
    }

    /******************************************************************/
    /* Channel                                                        */
    /******************************************************************/

    public static class Channel {
        private final Semaphore head = new Semaphore(0);
        private final Semaphore tail = new Semaphore(1);
        private Object data = null;
    }

    public static void chan_put(Channel chan, Object data)
            throws InterruptedException {
        sem_acquire(chan.tail);
        chan.data = data;
        sem_release(chan.head);
    }

    public static Object chan_take(Channel chan)
            throws InterruptedException {
        sem_acquire(chan.head);
        Object res = chan.data;
        chan.data = null;
        sem_release(chan.tail);
        return res;
    }

    /******************************************************************/
    /* os_chan_new/1 and ir_is_chan/1                                 */
    /******************************************************************/

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

    /**
     * ir_is_chan(O): internal only
     * The predicate succeeds if O is a channel.
     */
    private static boolean test_ir_is_chan(Object[] args) {
        Object obj = Machine.exec_build(args[0]);
        return (obj instanceof Channel);
    }

    /******************************************************************/
    /* os_chan_put/3 and os_chan_take/3                               */
    /******************************************************************/

    /**
     * test_os_chan_put(C, Q, P): internal only
     * The predicate succeeds in P with a promise that
     * sends the quote Q to the channel C.
     */
    private static boolean test_os_chan_put(Object[] args) {
        Object chan = Machine.exec_build(args[0]);
        check_channel(chan);
        Object data = Machine.exec_build(args[1]);
        return Machine.exec_unify(args[2],
                os_put_promise(Machine.engine, (Channel)chan, data));
    }

    private static Handler.Promise os_put_promise(Machine.Engine en, Channel chan, Object data) {
        return new Handler.Promise(() -> {
            Thread self = Thread.currentThread();
            en.abort = self::interrupt;
            try {
                chan_put(chan, data);
            } catch (InterruptedException x) {
                /* */
            } finally {
                en.abort = () -> {};
            }
        });
    }

    /**
     * test_os_chan_take(C, M, P): internal only
     * The predicate succeeds in P with a promise that
     * receives a quote into the map M from the channel C.
     */
    private static boolean test_os_chan_take(Object[] args) {
        Object chan = Machine.exec_build(args[0]);
        check_channel(chan);
        Map map = (Map)Machine.exec_build(args[1]);
        return Machine.exec_unify(args[2],
                os_take_promise(Machine.engine, (Channel)chan, map));
    }

    private static Handler.Promise os_take_promise(Machine.Engine en, Channel chan, Map map) {
        return new Handler.Promise(() -> {
            Thread self = Thread.currentThread();
            en.abort = self::interrupt;
            try {
                Object data = chan_take(chan);
                map.put("data", data);
            } catch (InterruptedException x) {
                /* */
            } finally {
                en.abort = () -> {};
            }
        });
    }

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

    /******************************************************************/
    /* Event                                                          */
    /******************************************************************/

    public static class Event {
        boolean set;

        /**
         * Create a boolean with multiple waiters.
         */
        public Event() {
            this.set = false;
        }

    }

    public static boolean event_is(Event evnt) {
        return evnt.set;
    }

    public static void event_set(Event evnt) {
        synchronized (evnt) {
            evnt.set = true;
            evnt.notifyAll();
        }
    }

    public static void event_wait(Event evnt)
            throws InterruptedException {
        synchronized (evnt) {
            while (!evnt.set)
                evnt.wait();
        }
    }

    /******************************************************************/
    /* os_task_create/2, os_task_list/1 and os_task_alive/1           */
    /******************************************************************/

    /**
     * os_task_create(N, E): internal only
     * The predicate succeeds in E with a new task for the compiled
     * goal N. The task is scheduled to execute immediately.
     */
    private static boolean test_os_task_create(Object[] args) {
        Object goal = Machine.exec_build(args[0]);
        special.check_goal(goal);
        Machine.Context tsk = new Machine.Context();
        siglib.setDelay(() -> task_async(goal, tsk, Machine.VOID_ARGS), 0);
        return Machine.exec_unify(args[1], tsk);
    }

    private static final ArrayList tasks = new ArrayList();

    public static void task_async(Object form, Machine.Context tsk, Object[] paras) {
        tsk.ref.done = new Event();
        tasks.add(tsk);
        try {
            Machine.launch_async(form, tsk, paras);
        } catch (Throwable err) {
            /* */
        } finally {
            event_set((Event)tsk.ref.done);
            int k = tasks.indexOf(tsk);
            tasks.remove(k);
        }
    }

    /**
     * os_task_list(L): internal only
     * The predicate succeeds in L with a snapshot of the alive tasks.
     */
    private static boolean test_os_task_list(Object[] args) {
        Object res = "[]";
        for (int i = tasks.size() - 1; i >= 0; i--)
            res = new Store.Compound(".", new Object[]{tasks.get(i), res});
        return Machine.exec_unify(args[0], res);
    }

    /**
     * os_task_alive(T): internal only
     * The predicate succeeds if the task T is alive.
     */
    private static boolean test_os_task_alive(Object[] args) {
        Object tsk = Machine.exec_build(args[0]);
        special.check_task(tsk);
        Machine.Engine en = Machine.determine_engine(tsk);
        return !event_is((Event) en.done);
    }

    /******************************************************************/
    /* os_task_join/2                                                 */
    /******************************************************************/

    /**
     * os_task_join(T, P): internal only
     * The predicate succeeds in P with a promise for the task T to die.
     */
    private static boolean test_os_task_join(Object[] args) {
        Object tsk = Machine.exec_build(args[0]);
        special.check_task(tsk);
        Machine.Engine en2 = Machine.determine_engine(tsk);
        return Machine.exec_unify(args[1],
                task_join_promise(Machine.engine, en2));
    }

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

    /******************************************************************/
    /* Evnt Lib Init                                                  */
    /******************************************************************/

    public static void main() {
        Store.set("ir_quote_new", 2, special.make_check(evntlib::test_ir_quote_new));
        Store.set("ir_quote_current", 2, special.make_special(evntlib::special_ir_quote_current));
        Store.set("os_chan_new", 1, special.make_check(evntlib::test_os_chan_new));
        Store.set("ir_is_chan", 1, special.make_check(evntlib::test_ir_is_chan));
        Store.set("os_chan_put", 3, special.make_check(evntlib::test_os_chan_put));
        Store.set("os_chan_take", 3, special.make_check(evntlib::test_os_chan_take));
        Store.set("os_task_create", 2, special.make_check(evntlib::test_os_task_create));
        Store.set("os_task_list", 1, special.make_check(evntlib::test_os_task_list));
        Store.set("os_task_alive", 1, special.make_check(evntlib::test_os_task_alive));
        Store.set("os_task_join", 2, special.make_check(evntlib::test_os_task_join));
    }

}
