# -*- coding: utf-8 -*-
#
#*******************************************************************************
#
#  Copyright 2022 RIEGL Laser Measurement Systems
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
#  SPDX-License-Identifier: Apache-2.0
#
#*******************************************************************************
#
"""
Basic handling of RDB library
"""

import ctypes
import os
import platform

# library handle object
handle = None


class RDBLIB(ctypes.CDLL):
    def __getitem__(self, name_or_ordinal):
        result = ctypes.CDLL.__getitem__(self, name_or_ordinal)
        if isinstance(name_or_ordinal, str) and name_or_ordinal.endswith("_cf"):
            # context-free functions return a pointer
            result.restype = ctypes.c_void_p
        else:
            # all other functions return an error code
            result.restype = ctypes.c_int32
        return result


def load():
    """
    Load RDB library

    The RDB library is expected to be located within the RDB Python package
    """
    if platform.system() == "Windows":
        name = "rdblib.dll"
    elif platform.system() == "Linux":
        name = "librdb.so.2"
    elif platform.system() == "Darwin":
        name = "librdb.2.dylib"
    else:
        raise NotImplementedError("Operating system not supported.")

    global handle
    path = os.path.abspath(os.path.dirname(__file__))
    full = os.path.join(path, name)
    if os.path.exists(full):  # prefer local library
        handle = RDBLIB(full)
    else:  # try library name without path
        handle = RDBLIB(name)


def free():
    """Unload RDB library"""
    global handle
    handle = None
