package doglet.util;

import nova.*;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 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 class siglib {

    /******************************************************************/
    /* os_sleep_promise/2                                             */
    /******************************************************************/

    /**
     * os_sleep_promise(D, P):
     * The predicate succeeds in P with a promise for a delay of D seconds.
     */
    private static boolean test_os_sleep_promise(Object[] args) {
        Object obj = Machine.exec_build(args[0]);
        special.check_number(obj);
        double delay = special.narrow_float((Number)obj);
        if (delay < 0)
            throw Machine.make_error(new Store.Compound("domain_error",
                    new Object[]{"not_less_than_zero", obj}));
        long delayms = Math.round(delay*1000);
        return Machine.exec_unify(args[1],
                sleep_promise(Machine.engine, delayms));
    }

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

    /**************************************************************/
    /* os_call_later/3 and timer_cancel/1                       */
    /**************************************************************/

    private static Timer timer = null;

    private static Timer getTimer() {
        if (timer == null)
            timer = new Timer(true);
        return timer;
    }

    /**
     * os_call_later(N, D, T): internal only
     * The predicate succeeds in T with a new timer. As a side effect
     * it schedules the compiled goal N to be executed after D seconds.
     */
    private static boolean test_os_call_later(Object[] args) {
        Object goal = Machine.exec_build(args[0]);
        special.check_goal(goal);
        Object obj = Machine.exec_build(args[1]);
        special.check_number(obj);
        double delay = special.narrow_float((Number)obj);
        if (delay < 0)
            throw Machine.make_error(new Store.Compound("domain_error",
                    new Object[]{"not_less_than_zero", obj}));
        long delayms = Math.round(delay*1000);
        Object buf = Machine.ctx;
        TimerTask tid = setDelay(() ->
                callback(goal, buf, Machine.VOID_ARGS), delayms);
        return Machine.exec_unify(args[2], tid);
    }

    private static boolean callback(Object form, Object buf, Object[] paras) {
        try {
            return Machine.launch(form, buf, paras);
        } catch (Throwable err) {
            return false;
        }
    }

    /**
     * timer_cancel(T):
     * The predicate succeeds. As a side effect it cancels the timer T.
     */
    private static boolean test_timer_cancel(Object[] args) {
        Object obj = Machine.exec_build(args[0]);
        check_timer(obj);
        ((TimerTask) obj).cancel();
        return true;
    }

    public static void check_timer(Object beta) {
        if (!(beta instanceof TimerTask)) {
            Store.check_nonvar(beta);
            beta = Store.copy_term(beta);
            throw Machine.make_error(new Store.Compound("type_error",
                    new Object[]{"timer", beta}));
        }
    }

    /**
     * Delay a coroutine by some milliseconds.
     *
     * @param proc The coroutine.
     * @param delay The milliseconds.
     * @return The timer.
     */
    public static TimerTask setDelay(Runnable proc, long delay) {
        TimerTask tid = new Later(proc);
        Timer timer = getTimer();
        timer.schedule(tid, delay);
        return tid;
    }

    private static class Later extends TimerTask {
        Runnable proc;

        public Later(Runnable proc) {
            this.proc = proc;
        }

        public void run() {
            new Handler.Coroutine(() -> proc.run()).async();
        }
    }

    /******************************************************************/
    /* Sig Lib Init                                                   */
    /******************************************************************/

    public static void main() {
        Store.set("os_sleep_promise", 2, special.make_check(siglib::test_os_sleep_promise));
        Store.set("os_call_later", 3, special.make_check(siglib::test_os_call_later));
        Store.set("timer_cancel", 1, special.make_check(siglib::test_timer_cancel));
    }

}
