from ctypes import c_void_p, c_int, c_int64, c_uint8, CFUNCTYPE
from ctypes import cdll
from typing import Any
import platform
import sys


def load_library(name):
    return cdll.LoadLibrary(name)


def _load_library() -> Any:
    os_system = platform.system().lower()
    os_machine = platform.machine().lower()
    if os_machine.startswith("arm"):
        arch = "arm"
    else:
        arch = "amd64" if sys.maxsize > 2**32 else "386"
    ext = ""
    if os_system == "linux":
        ext = ".so"
    if os_system == "darwin":
        ext = ".dylib"
    lib_name = "zaber-motion-lib-{}-{}{}".format(os_system, arch, ext)
    return load_library(lib_name)


lib = _load_library()

CALLBACK = CFUNCTYPE(None, c_void_p, c_int64)

c_call = lib.call
c_call.argtypes = [c_void_p, c_int64, CALLBACK, c_uint8]
c_call.restype = c_int

c_set_event_handler = lib.setEventHandler
c_set_event_handler.argtypes = [c_int64, CALLBACK]
c_set_event_handler.restype = None
