###
# 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, objects_list, make_check, deref, unify,
    exec_build, exec_unify, array_last_index, check_task,
    check_goal, Context, make_special, for_later,
    launch_async, VOID_ARGS, determine_engine, freeze_quote,
    melt_quote, cont, get_cont, check_nonvar, copy_term,
    make_error, Compound, get_engine)
import asyncio


#####################################################################
# 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.
##
def test_ir_quote_new(args):
    alpha = exec_build(args[0])
    alpha = freeze_quote(alpha)
    return 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.
##
def special_ir_quote_current(args):
    alpha = deref(args[0])
    alpha = melt_quote(alpha)
    if not unify(args[1], alpha):
        return False
    cont(get_cont().args[1])
    return True


#####################################################################
# Waitable                                                          #
#####################################################################

class Waiter:
    def __init__(self):
        self.callback = None
        self.owner = None


class Waitable:
    def __init__(self):
        self.waiters = []


def waitable_notify(obj, count):
    mlist = obj.waiters
    if count == 0:
        count = len(mlist)
    while len(mlist) > 0 and count > 0:
        waiter = mlist[0]
        mlist.pop(0)
        waiter.callback(True)
        count -= 1


async def waitable_wait(obj, owner):
    loop = asyncio.get_running_loop()
    future = loop.create_future()
    waiter = Waiter()
    waiter.callback = lambda res: future.set_result(res)
    waiter.owner = owner
    obj.waiters.append(waiter)
    return await future


def waitable_cancel(obj, owner):
    mlist = obj.waiters
    i = 0
    while i < len(mlist):
        if mlist[i].owner == owner:
            break
        i += 1
    if i < len(mlist):
        waiter = mlist[i]
        mlist.pop(i)
        waiter.callback(False)


#####################################################################
# Semaphore                                                         #
#####################################################################

class Semaphore(Waitable):
    def __init__(self, permits):
        super().__init__()
        self.permits = permits


def sem_release(sem):
    sem.permits += 1
    waitable_notify(sem, 1)


async def sem_acquire(sem, owner):
    while sem.permits == 0:
        if not await waitable_wait(sem, owner):
            return False
    sem.permits -= 1
    return True


#####################################################################
# Channel                                                           #
#####################################################################

class Channel:
    def __init__(self):
        self.head = Semaphore(0)
        self.tail = Semaphore(1)
        self.data = None


async def chan_put(chan, data, owner):
    if not await sem_acquire(chan.tail, owner):
        return False
    chan.data = data
    sem_release(chan.head)
    return True


def chan_unput(chan, owner):
    waitable_cancel(chan.tail, owner)


async def chan_take(chan, owner):
    if not await sem_acquire(chan.head, owner):
        return NotImplemented
    res = chan.data
    chan.data = None
    sem_release(chan.tail)
    return res


def chan_untake(chan, owner):
    waitable_cancel(chan.head, owner)


#####################################################################
# 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.
##
def test_os_chan_new(args):
    res = Channel()
    return exec_unify(args[0], res)


###
# test_ir_is_chan(O): internal only
# The predicate succeeds if O is a channel.
##
def test_ir_is_chan(args):
    obj = exec_build(args[0])
    return isinstance(obj, 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.
##
def test_os_chan_put(args):
    chan = exec_build(args[0])
    check_channel(chan)
    data = exec_build(args[1])
    return exec_unify(args[2], for_later(
        os_put_promise(get_engine(), chan, data)))


async def os_put_promise(en, chan, data):
    en.abort = lambda: chan_unput(chan, en)
    await chan_put(chan, data, en)
    en.abort = lambda: None


###
# 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.
##
def test_os_chan_take(args):
    chan = exec_build(args[0])
    check_channel(chan)
    mmap = exec_build(args[1])
    return exec_unify(args[2], for_later(
        os_take_promise(get_engine(), chan, mmap)))


async def os_take_promise(en, chan, mmap):
    en.abort = lambda: chan_untake(chan, en)
    data = await chan_take(chan, en)
    if data is not NotImplemented:
        mmap["data"] = data
    en.abort = lambda: None


###
# check_channel(beta): internal only
# The predicate checks if beta is a channel.
##
def check_channel(beta):
    if not isinstance(beta, Channel):
        check_nonvar(beta)
        beta = copy_term(beta)
        raise make_error(Compound("type_error", ["channel", beta]))


#####################################################################
# Event                                                             #
#####################################################################

class Event(Waitable):
    def __init__(self):
        super().__init__()
        self.set = False


def event_is(evnt):
    return evnt.set


def event_set(evnt):
    evnt.set = True
    waitable_notify(evnt, 0)


async def event_wait(evnt, owner):
    while not evnt.set:
        if not await waitable_wait(evnt, owner):
            return False
    return True


#####################################################################
# 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 executed immediately.
##
def test_os_task_create(args):
    goal = exec_build(args[0])
    check_goal(goal)
    tsk = Context()
    loop = asyncio.get_running_loop()
    loop.create_task(task_async(goal, tsk, VOID_ARGS))
    return exec_unify(args[1], tsk)


tasks = []


async def task_async(form, tsk, paras):
    tsk.ref.done = Event()
    tasks.append(tsk)
    try:
        await launch_async(form, tsk, paras)
    except BaseException:
        pass
    finally:
        event_set(tsk.ref.done)
        k = array_last_index(tasks, tsk)
        del tasks[k]


###
# os_task_list(L): internal only
# The predicate succeeds in L with a snapshot of the launched tasks.
##
def test_os_task_list(args):
    res = objects_list(tasks, 0, len(tasks))
    return exec_unify(args[0], res)


###
# os_task_alive(T): internal only
# The predicate succeeds if the task T is alive.
##
def test_os_task_alive(args):
    tsk = exec_build(args[0])
    check_task(tsk)
    en = determine_engine(tsk)
    return not event_is(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.
##
def test_os_task_join(args):
    tsk = exec_build(args[0])
    check_task(tsk)
    en2 = determine_engine(tsk)
    return exec_unify(args[1], for_later(
        task_join_promise(get_engine(), en2)))


async def task_join_promise(en, en2):
    en.abort = lambda: waitable_cancel(en2.done, en)
    await event_wait(en2.done, en)
    en.abort = lambda: None


#####################################################################
# Evnt Lib Init                                                     #
#####################################################################

def main():
    set("ir_quote_new", 2, make_check(test_ir_quote_new))
    set("ir_quote_current", 2, make_special(special_ir_quote_current))
    set("os_chan_new", 1, make_check(test_os_chan_new))
    set("ir_is_chan", 1, make_check(test_ir_is_chan))
    set("os_chan_put", 3, make_check(test_os_chan_put))
    set("os_chan_take", 3, make_check(test_os_chan_take))
    set("os_task_create", 2, make_check(test_os_task_create))
    set("os_task_list", 1, make_check(test_os_task_list))
    set("os_task_alive", 1, make_check(test_os_task_alive))
    set("os_task_join", 2, make_check(test_os_task_join))
