###
# 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.
##

from nova.core import (
    set, make_check, exec_build, exec_unify, get_ctx,
    make_error, Compound, get_engine,
    for_later, check_number, narrow_float,
    check_nonvar, copy_term, launch, check_goal, VOID_ARGS)
import asyncio


#####################################################################
# os_sleep_promise/2                                                #
#####################################################################

###
# os_sleep_promise(D, P):
# The predicate succeeds in P with a promise for a delay of D seconds.
##
def test_os_sleep_promise(args):
    obj = exec_build(args[0])
    check_number(obj)
    delay = narrow_float(obj)
    if delay < 0:
        raise make_error(Compound("domain_error",
                      ["not_less_than_zero", obj]))
    return exec_unify(args[1], for_later(
        sleep_promise(get_engine(), delay)))


async def sleep_promise(en, delay):
    en.abort = asyncio.current_task().cancel
    try:
        await asyncio.sleep(delay)
    except asyncio.CancelledError:
        pass
    finally:
        en.abort = lambda: None


################################################################
# os_call_later/3 and timer_cancel/1                           #
################################################################

###
# 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.
##
def test_os_call_later(args):
    goal = exec_build(args[0])
    check_goal(goal)
    obj = exec_build(args[1])
    check_number(obj)
    delay = narrow_float(obj)
    if delay < 0:
        raise make_error(Compound("domain_error",
                      ["not_less_than_zero", obj]))
    buf = get_ctx()
    loop = asyncio.get_running_loop()
    tid = loop.call_later(delay,
                  lambda: callback(goal, buf, VOID_ARGS))
    return exec_unify(args[2], tid)


def callback(form, buf, paras):
    try:
        return launch(form, buf, paras)
    except BaseException:
        return False


###
# timer_cancel(T):
# The predicate succeeds. As a side effect it cancels the timer T.
##
def test_timer_cancel(args):
    res = exec_build(args[0])
    check_timer(res)
    res.cancel()
    return True


def check_timer(beta):
    if not isinstance(beta, asyncio.TimerHandle):
        check_nonvar(beta)
        beta = copy_term(beta)
        raise make_error(Compound("type_error", ["timer", beta]))


#####################################################################
# Sig Lib Init                                                      #
#####################################################################

def main():
    set("os_sleep_promise", 2, make_check(test_os_sleep_promise))
    set("os_call_later", 3, make_check(test_os_call_later))
    set("timer_cancel", 1, make_check(test_timer_cancel))
