# -*- 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
#
#*******************************************************************************
#
"""
Various utility functions
"""

from ctypes import c_char_p


def to_rdb_string(value):
    """
    Convert standard string to RDB string

    Args:
        value: object of type str to be converted to an RDB string
    """
    return c_char_p(None) if value is None else c_char_p(str(value).encode(encoding="utf-8", errors="replace"))


def to_std_string(buffer):
    """
    Convert RDB string to standard string

    Args:
        buffer: object of type ctypes.c_char_p that will be converted to a str
    """
    return str() if buffer is None else buffer.value.decode(encoding="utf-8", errors="replace")


def to_std_strings(buffer, count):
    """
    Convert list of RDB strings to list of standard strings

    Args:
        buffer: ctypes.POINTER(c_char) that points to list of strings
        count: number of strings contained in string list
    """
    i = 0
    items = list()
    chars = bytes()
    while len(items) < count:
        if ord(buffer[i]) != 0:
            chars += buffer[i]
        else:
            items.append(chars.decode(encoding="utf-8", errors="replace"))
            chars = bytes()
        i += 1
    return items
