#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName   : logProcess.py
@Account    : Administrator
@Time       : 2025/8/13 12:40
@Author     : xsh
@Description: 
"""
from PyQt5 import Qt
from multiprocessing import  Process, Pool, pool, Manager, Queue
import itertools
import multiprocessing
from AppLog.logInterface import logInterface
from AppLog.logSingleton import logSingleton
from AppLog.logEvent import logEvent
from AppLog.logUtils import logUtils

def sendLogger(fp: Qt.QFile, buffer: str) -> int:
    isWrong: int = 0
    end_times: Qt.QDateTime = Qt.QDateTime.currentDateTime().addMSecs(2000)
    if not isinstance(fp, Qt.QFile) or not fp.isOpen():
        return isWrong
    stream: Qt.QTextStream = Qt.QTextStream(fp)
    stream.setCodec("UTF-8")
    stream << buffer << '\r\n'
    stream.flush()
    while True:
        if stream.status() == Qt.QTextStream.Ok:
            break
        if Qt.QDateTime.currentDateTime() > end_times:
            break
        stream.flush()
        logUtils.processEvent(50)
    isWrong = 1 if stream.status() == Qt.QTextStream.Ok else 0
    return isWrong


class CustomProcess(Process):
    Buffer: Queue  # 缓存
    is_running: bool
    def __init__(self):
        super().__init__()
        self.initBuffer()
        self.is_running = False


    def initBuffer(self):
        if not self.hasBuffer:
            self.Buffer = Queue()

    def appendItem(self, event: logEvent):
        self.initBuffer()
        try:
            self.Buffer.put({'FILE': event.FILE, 'BUFF': event.BUFF})
        except Exception as e:
            logUtils.print_Exception(e)

    @property
    def hasBuffer(self) -> bool:
        return hasattr(self, 'Buffer') and self.Buffer is not None

    def run(self) -> None:
        self.is_running = True

        while True:
            if not self.is_running:
                break
            try:
                data: dict[Qt.QFile, str] = self.Buffer.get()
                try:
                    if isinstance(data, dict):
                        sendLogger(data['FILE'], data['BUFF'])
                except Exception as processE:
                    logUtils.print_Exception(processE)

                self.Buffer.task_done()
            except Exception as e:
                logUtils.print_Exception(e)



class logProcess(Qt.QObject, logInterface, logSingleton):
    Course  : CustomProcess         # 进程
    Locker: Qt.QMutex = Qt.QMutex()

    @classmethod
    def GetInstance(cls, *args, **kwargs) -> 'logProcess':
        return super(logProcess, cls).GetInstance(*args, **kwargs)

    def __init__(self, parent: Qt.QObject = None):
        super(logProcess, self).__init__(parent=parent)
        self.Initialization('logProcess', self, parent)

    def initValue(self):
        super(logProcess, self).initValue()
        self.initCourse()


    def initCourse(self):
        if not self.hasCourse:
            self.Course = CustomProcess()
        if not self.isActive:
            self.Course.start()

    def appendItem(self, event: logEvent):
        self.initCourse()
        self.Course.appendItem(event)

    @property
    def isActive(self) -> bool:
        return self.hasCourse and self.Course.is_alive()

    def start(self):
        self.initCourse()


    def stop(self):
        if not self.hasCourse:
            return
        if self.isActive:
            self.Course.is_running = False
            self.Course.join(1000)




    @property
    def hasCourse(self) -> bool:
        return hasattr(self, 'Course') and isinstance(self.Course, Process)
