# -*- coding: utf-8 -*-
import random
import uuid

keyNumber = "0123456789"
keyLower = "abcdefghijklmnopqrstuvwxyz"
keyUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
keyChars = keyNumber + keyLower + keyUpper


class NString:

    @staticmethod
    def guid() -> str:
        """ 获取guid

        Returns:
            str: guid
        """
        return str(uuid.uuid4())

    @staticmethod
    def uuid(length: int = 0):
        chars = list(keyChars)
        result = []

        radix = len(chars)
        if length > 0:
            # 生成指定长度的随机ID
            for _ in range(length):
                result.append(chars[random.randint(0, radix - 1)])
        else:
            # 生成标准UUID格式的ID
            result = ['-'] * 36
            result[14] = '4'

            for i in range(36):
                if result[i] == '-':
                    continue
                r = random.randint(0, 15)
                if i == 19:
                    result[i] = chars[(r & 0x3) | 0x8]
                else:
                    result[i] = chars[r]

        return ''.join(result)

    @staticmethod
    def get_hex_string(length=16):
        result = ''.join(random.choice(keyChars) for _ in range(length))
        return result

    @staticmethod
    def to_hex_string(s: str):
        if s is None or len(s) <= 0:
            return ''
        return ''.join(format(ord(c), '02x') for c in s)

    @staticmethod
    def hex_to_string(hex_str: str):
        if hex_str is None or len(hex_str) <= 0:
            return ''
        return bytes.fromhex(hex_str).decode('utf-8')

    @staticmethod
    def to_buffer(txt: str):
        if txt is None or len(txt) <= 0:
            return b''
        return txt.encode("utf-8")

    @staticmethod
    def strip_newlines_from_values(data):
        if isinstance(data, dict):
            return {
                key: NString.strip_newlines_from_values(value)
                for key, value in data.items()
            }
        elif isinstance(data, list):
            return [NString.strip_newlines_from_values(item) for item in data]
        elif isinstance(data, str):
            return data.rstrip('\n')
        else:
            return data
