#encoding = utf8

from ctypes import *
import os

import numpy as np

current = os.path.dirname(__file__)
dynamic_path = os.path.join(current, 'AudioRender.dll')


def audio_render_log_callback(level, log, size):
    print(f'level={level}, log={log}, len={size}')


class AudioRender:
    def __init__(self):
        self.__audio_render_obj = WinDLL(dynamic_path)
        print(self.__audio_render_obj)
        if self.__audio_render_obj is not None:
            CALLBACK_TYPE = CFUNCTYPE(None, c_int, c_ubyte, c_uint)
            c_callback = CALLBACK_TYPE(audio_render_log_callback)
            self.__init = self.__audio_render_obj.Initialize(c_callback)
            print('AudioRender init', self.__init)

    def __del__(self):
        print('AudioRender __del__')
        if self.__audio_render_obj is None:
            return
        if self.__init:
            self.__audio_render_obj.Uninitialize()

    def write(self, data, size):
        if not self.__init:
            return False

        self.__audio_render_obj.argtypes = (POINTER(c_uint8), c_uint)
        byte_data = np.frombuffer(data, dtype=np.uint8)
        return self.__audio_render_obj.Write(byte_data.ctypes.data_as(POINTER(c_uint8)), size)
