# encoding:utf-8
'''
(ok)
'''
import os
import ctypes
import platform

Voice_Record_Callback = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
                                         ctypes.POINTER(ctypes.c_char))


def read_config_file(filename):
    with open(filename, 'r') as file:
        return file.read()


class VoiceRecord:
    def __init__(self, callback=None):
        pwd = os.path.dirname(__file__)
        if platform.architecture()[0] == '32bit':
            self.dll = ctypes.CDLL(os.path.join(pwd, "aiplay32.dll"))
        else:
            self.dll = ctypes.CDLL(os.path.join(pwd, "aiplay64.dll"))

        self.dll.voice_record_init.argtypes = [ctypes.c_char_p, Voice_Record_Callback]
        self.dll.voice_record_init.restype = ctypes.c_int
        self.dll.voice_record_start.argtypes = []
        self.dll.voice_record_start.restype = ctypes.c_int
        self.dll.voice_record_stop.argtypes = []
        self.dll.voice_record_stop.restype = ctypes.c_int
        self.dll.voice_record_deinit.argtypes = []
        self.dll.voice_record_deinit.restype = None
        auth_code = read_config_file('auth.cfg')
        self.callback = Voice_Record_Callback(callback)
        rc = self.dll.voice_record_init(auth_code.encode('utf-8'), self.callback)
        print(f'voice_record_init:{rc}')
        if rc != 0:
            raise Exception("初始化失败")

    def __del__(self):
        self.dll.voice_record_deinit()

    def voice_record_start(self):
        return self.dll.voice_record_start()

    def voice_record_stop(self):
        return self.dll.voice_record_stop()
