from PyQt5.QtCore import QObject, pyqtSignal, QThread
import os
from util import my_util, constants


class ReadFile(QObject):
    trigger = pyqtSignal(dict)

    def __init__(self):
        super(ReadFile, self).__init__()
        self._dir = ""
        self._stop_flag = False

    def update_work_dir(self, _dir):
        self._dir = _dir
        self._stop_flag = False

    def work(self):
        if not self._dir:
            return
        for fp in os.listdir(self._dir):
            if self._stop_flag:
                return
            _file = f"{self._dir}/{fp}"
            if os.path.isfile(_file):
                self.trigger.emit(my_util.gen_q_data(constants.AITEST_FILE_NAME, fp))
                QThread.sleep(1)
                with open(_file, "rb") as f:
                    while True:
                        if self._stop_flag:
                            self.trigger.emit(my_util.gen_q_data(constants.AITEST_FILE_END, 0))
                            return
                        buf = f.read(640)
                        if not buf:
                            self.trigger.emit(my_util.gen_q_data(constants.AITEST_FILE_END, 1))
                            QThread.sleep(1)
                            break
                        else:
                            self.trigger.emit(my_util.gen_q_data(constants.AITEST_FILE_BUF, buf))
                            QThread.msleep(16)
        self.trigger.emit(my_util.gen_q_data(constants.AITEST_FILE_END, 2))

    def stop_work(self):
        self._stop_flag = True


class SendAudio(QObject):
    def __init__(self, queue):
        super(SendAudio, self).__init__()
        self.queue = queue
        self._stop_flag = False
        self.send_audio = None

    def update_func(self, send_func):
        self.send_audio = send_func

    def work(self):
        while True:
            if self._stop_flag:
                return
            if not self.queue.empty():
                buf = self.queue.get()
                if self.send_audio:
                    self.send_audio(buf)
                    continue
            QThread.msleep(20)

    def stop_work(self):
        self._stop_flag = True


class WriteResult(QObject):
    def __init__(self, queue):
        super(WriteResult, self).__init__()
        self.queue = queue
        self._stop_flag = False
        self._file = None

    def update_filename(self, file_name):
        self._file = file_name

    def work(self):
        while True:
            if self._stop_flag:
                return
            if not self.queue.empty():
                text = self.queue.get()
                f = open(self._file, "a", encoding="utf-8")
                f.write(text)
                f.close()
                continue
            QThread.msleep(20)

    def stop_work(self):
        self._stop_flag = True
