# encoding:utf-8
'''
主进程UI的子线程，除UI外必须在主进程处理的业务
'''
import ctypes
import logging

from PyQt5.QtCore import QThread, pyqtSignal

from util import constants
from util import my_util
from win import aiplay


class Mspeech(QThread):
    sign_thread_recv = pyqtSignal(dict)
    sign_thread_send = pyqtSignal(dict)
    _logger = logging.getLogger(__name__)

    def __init__(self):
        super().__init__()
        self.sign_thread_recv.connect(self._proc_data)

    def __del__(self):
        pass

    def run(self):
        self._init_device()
        pass

    # 向主线程发送数据
    def _send_data(self, data):
        try:
            # 给主线程传递数据
            self.sign_thread_send.emit(data)
        except Exception as e:
            print(e)

    # 处理收到主线程发送的数据
    def _proc_data(self, data):
        self._logger.info(data)
        code = data["code"]
        print("UI_th_proc_data", code)

    # 初始化设备
    def _init_device(self):
        self.bundle_lib = aiplay.VoiceRecord(self.callback)
        rc = self.bundle_lib.voice_record_start()
        if rc == 0:
            print("开启录音成功")
        else:
            print("开启录音失败")

    # 定义回调函数
    def callback(self, event, arg1, arg2, data):
        # 在这里处理回调数据
        # print(f"Event: {event}, arg1: {arg1}, arg2: {arg2}")
        if event == 0x01:  # E_EVENT_VOICE_BTN_DOWN
            print("语言键按下")
            self._send_data(my_util.gen_q_data(constants.MSPEECH_AIUI_RESET_DICTATION, None))
        elif event == 0x02:  # E_EVENT_VOICE_BTN_UP
            print("语言键松开")
            self._send_data(my_util.gen_q_data(constants.MSPEECH_AIUI_STOP_WS, None))
        elif event == 0x03:  # E_EVENT_VOICE_DATE
            buf = ctypes.cast(data, ctypes.POINTER(ctypes.c_char * arg1)).contents.raw
            self._send_data(my_util.gen_q_data(constants.MSPEECH_AIUI_SEND_DATA, buf))
        elif event == 251:
            # 251：演示笔插入  252：演示笔拔出  255：错误没有检测到录音笔设备
            print("演示笔热插拔")
            self.bundle_lib.voice_record_stop()
            self.bundle_lib.voice_record_start()
