###
# 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, deref, is_structure, make_check, MAX_ARITY, check_nil,
    exec_build, exec_unify, int32, Compound, for_later,
    check_integer, check_nonvar, copy_term, make_error, get_engine)
import threading
import asyncio


MAX_DATA = 128


#######################################################################
# CPU Semaphore Class                                                 #
#######################################################################

class Semaphore:
    def __init__(self, permits):
        self.cond = threading.Condition(threading.Lock())
        self.permits = permits


def cpu_lock_acquire(lock, en):
    with lock.cond:
        while en is None or en.signal is NotImplemented:
            if lock.permits == 0:
                lock.cond.wait()
                continue
            lock.permits -= 1
            return True
        return False


def cpu_lock_cancel(lock):
    with lock.cond:
        lock.cond.notify_all()


def cpu_lock_tryacquire(lock):
    with lock.cond:
        if lock.permits == 0:
            return False
        lock.permits -= 1
        return True


def cpu_lock_release(lock):
    with lock.cond:
        lock.permits += 1
        lock.cond.notify()


#######################################################################
# CPU Crossbar Class                                                  #
#######################################################################

class Crossbar:
    def __init__(self):
        self.head = Semaphore(0)
        self.tail = Semaphore(1)
        self.data = [0] * (1+MAX_DATA)


def cpu_data_store(data, src, offset, mlen):
    data[0] = mlen
    i = 0
    while i < mlen:
        data[1+i] = src[offset+i]
        i += 1


###
# cpu_data_load(src, dst, offset, len):
# Unlike streams, this is an all or nothing load.
# return: != len if nothing loaded, otherwise everything loaded.
##
def cpu_data_load(data, dst, offset, mlen):
    res = data[0]
    if res != mlen:
        return res
    i = 0
    while i < mlen:
        dst[offset + i] = data[1 + i]
        i += 1
    return mlen


def cpu_xbar_put(xbar, src, offset, mlen, en):
    if not cpu_lock_acquire(xbar.tail, en):
        return False
    cpu_data_store(xbar.data, src, offset, mlen)
    cpu_lock_release(xbar.head)
    return True


def cpu_xbar_unput(xbar):
    cpu_lock_cancel(xbar.tail)


###
# cpu_xbar_take(xbar, dst, offset, len, en):
# Unlike streams, this is an all or nothing take.
# @return -1 if aborted, otherwise all or nothing.
##
def cpu_xbar_take(xbar, dst, offset, mlen, en):
    if not cpu_lock_acquire(xbar.head, en):
        return -1
    res = cpu_data_load(xbar.data, dst, offset, mlen)
    cpu_lock_release(xbar.tail)
    return res


def cpu_xbar_untake(xbar):
    cpu_lock_cancel(xbar.head)


def cpu_xbar_offer(xbar, src, offset, mlen):
    if not cpu_lock_tryacquire(xbar.tail):
        return False
    cpu_data_store(xbar.data, src, offset, mlen)
    cpu_lock_release(xbar.head)
    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.
##
def cpu_xbar_poll(xbar, dst, offset, mlen):
    if not cpu_lock_tryacquire(xbar.head):
        return -1
    res = cpu_data_load(xbar.data, dst, offset, mlen)
    cpu_lock_release(xbar.tail)
    return res


#######################################################################
# CPU Integer Arrays                                                  #
#######################################################################

###
# test_cpu_buf_new(A, B): internal only
# The predicate succeeds in H with the buffer from the list D.
##
def test_cpu_buf_new(args):
    alpha = exec_build(args[0])
    res = cpu_list_ints(alpha)
    return exec_unify(args[1], res)


def cpu_list_ints(obj):
    peek = obj
    i = 0
    while (is_structure(peek) and
           peek.functor == "." and
           len(peek.args) == 2 and
           i < MAX_ARITY):
        i += 1
        peek = deref(peek.args[1])
    check_nil(peek)
    args = [NotImplemented] * i
    peek = obj
    i = 0
    while (is_structure(peek) and
           peek.functor == "." and
           len(peek.args) == 2):
        val = deref(peek.args[0])
        check_integer(val)
        args[i] = int32(val)
        i += 1
        peek = deref(peek.args[1])
    return args


###
# test_cpu_buf_current(A, B): internal only
# The predicate succeeds in D with the list from the buffer H.
##
def test_cpu_buf_current(args):
    alpha = exec_build(args[0])
    res = cpu_ints_list(alpha, 0, len(alpha))
    return exec_unify(args[1], res)


def cpu_ints_list(alpha, off, count):
    res = "[]"
    i = off + count - 1
    while i >= off:
        res = Compound(".", [alpha[i], res])
        i -= 1
    return res


#######################################################################
# CPU Crossbar Interface                                               #
#######################################################################

###
# test_cpu_xbar_new(A): internal only
# The predicate succeeds in A with a new xbar.
##
def test_cpu_xbar_new(args):
    res = Crossbar()
    return 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.
##
def test_cpu_xbar_put(args):
    xbar = exec_build(args[0])
    check_xbar(xbar)
    data = exec_build(args[1])
    return exec_unify(args[2], for_later(
        cpu_put_promise(get_engine(), xbar, data)))


async def cpu_put_promise(en, xbar, data):
    en.abort = lambda: cpu_xbar_unput(xbar)
    try:
        await asyncio.to_thread(cpu_xbar_put, xbar, data, 0, len(data), en)
    finally:
        en.abort = lambda: None


###
# 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.
##
def test_cpu_xbar_take(args):
    xbar = exec_build(args[0])
    check_xbar(xbar)
    mmap = exec_build(args[1])
    return exec_unify(args[2], for_later(
        cpu_take_promise(get_engine(), xbar, mmap)))


async def cpu_take_promise(en, xbar, mmap):
    en.abort = lambda: cpu_xbar_untake(xbar)
    try:
        mlen = mmap["len"]
        data = [0] * mlen
        res = await asyncio.to_thread(cpu_xbar_take, xbar, data, 0, mlen, en)
        if res != mlen:
            mmap["len"] = res
        else:
            mmap["data"] = data
    finally:
        en.abort = lambda: None


###
# test_cpu_xbar_offer(C, H): internal only
# The predicate succeeds when it can send
# the buffer H to the xbar C.
##
def test_cpu_xbar_offer(args):
    xbar = exec_build(args[0])
    check_xbar(xbar)
    data = exec_build(args[1])
    return cpu_xbar_offer(xbar, data, 0, len(data))


###
# 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.
##
def test_cpu_xbar_poll(args):
    xbar = exec_build(args[0])
    check_xbar(xbar)
    mmap = exec_build(args[1])
    mlen = mmap["len"]
    data = [0] * mlen
    res = cpu_xbar_poll(xbar, data, 0, mlen)
    if res == -1:
        return False
    if res != mlen:
        mmap["len"] = res
    else:
        mmap["data"] = data
    return True


#######################################################################
# CPU Crossbar Arrays                                                  #
#######################################################################

###
# test_cpu_comm_new(A, B): internal only
# The predicate succeeds in H with the table from the list D.
##
def test_cpu_comm_new(args):
    alpha = exec_build(args[0])
    res = cpu_list_comm(alpha)
    return exec_unify(args[1], res)


def cpu_list_comm(obj):
    peek = obj
    i = 0
    while (is_structure(peek) and
           peek.functor == "." and
           len(peek.args) == 2 and
           i < MAX_ARITY):
        i += 1
        peek = deref(peek.args[1])
    check_nil(peek)
    args = [NotImplemented] * i
    peek = obj
    i = 0
    while (is_structure(peek) and
           peek.functor == "." and
           len(peek.args) == 2):
        val = deref(peek.args[0])
        check_xbar(val)
        args[i] = val
        i += 1
        peek = deref(peek.args[1])
    return args


def check_xbar(beta):
    if not isinstance(beta, Crossbar):
        check_nonvar(beta)
        beta = copy_term(beta)
        raise make_error(Compound("type_error",
                  ["xbar", beta]))


#######################################################################
# Chan Lib Init                                                       #
#######################################################################

def main():
    set("cpu_buf_new", 2, make_check(test_cpu_buf_new))
    set("cpu_buf_current", 2, make_check(test_cpu_buf_current))
    set("cpu_xbar_new", 1, make_check(test_cpu_xbar_new))
    set("cpu_xbar_put", 3, make_check(test_cpu_xbar_put))
    set("cpu_xbar_take", 3, make_check(test_cpu_xbar_take))
    set("cpu_xbar_offer", 2, make_check(test_cpu_xbar_offer))
    set("cpu_xbar_poll", 2, make_check(test_cpu_xbar_poll))
    set("cpu_comm_new", 2, make_check(test_cpu_comm_new))