#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName: logEvent.py
 @DateTime: 2025/6/21 16:52
 @SoftWare: PyCharm
 @Author  ：xsh
"""
from PyQt5 import Qt
from AppLog.LogLevel import LogLevel, LogMode
from AppLog.logUtils import logUtils, log_exception
from AppLog.logSlot import logSlot
class logEvent(Qt.QObject):

    FILE        : Qt.QFile
    DATE        : Qt.QDate
    BUFF        : str
    TYPE        : int
    MODE        : int

    @classmethod
    def instance(cls, **args) -> 'logEvent':
        result: cls = cls.__new__(cls)
        result.__init__(**args)
        return result

    def __init__(self, **args):
        super(logEvent, self).__init__()
        self.initEvent(**args)

    # def __del__(self):
    #     self.FILE = None
    #     self.BUFF = None
    #     self.TYPE = None
    #     self.DATE = None
    #     self.MODE = None
    #     super(logEvent, self).__del__()


    def getEvent(self) -> dict[str, object]:
        return {
            'FILE': self.FILE ,
            'BUFF': self.BUFF ,
            'TYPE': self.TYPE ,
            'DATE': self.DATE ,
            'MODE': self.MODE ,
        }

    def initEvent(self, **args):
        self.FILE = args.get('FILE', None               )
        self.BUFF = args.get('BUFF', None               )
        self.TYPE = args.get('TYPE', LogLevel.LOG_DEBUG )
        self.DATE = args.get('DATE', None               )
        self.MODE = args.get('MODE', LogMode.LOG_SEND   )

    def reopen(self):
        self.closeFILE(self.FILE)
        self.open(self.FILE, self.TYPE, self.MODE)

    def close(self):
        self.closeFILE(self.FILE)


    @property
    def isCurrentDate(self) -> bool:
        return self.has_DATE and self.DATE == Qt.QDate.currentDate()

    @property
    def isOpen(self) -> bool:
        return self.has_FILE and self.FILE.isOpen()

    @property
    def isAvailable(self) -> bool:
        return self.has_FILE and self.has_BUFF and self.FILE.isOpen()


    @property
    def has_FILE(self) -> bool:
        return hasattr(self, 'FILE') and isinstance(self.FILE, Qt.QFile   )

    @property
    def has_DATE(self) -> bool:
        return hasattr(self, 'DATE') and isinstance(self.DATE, Qt.QDate   )

    @property
    def has_BUFF(self) -> bool:
        return hasattr(self, 'BUFF') and isinstance(self.BUFF, str        )

    @property
    def has_TYPE(self) -> bool:
        return hasattr(self, 'TYPE') and isinstance(self.TYPE, int        )

    @log_exception
    def WaitDone(self, *args, **kwargs) -> int:
        isWrong = 0
        if not self.has_FILE:
            return isWrong
        if not self.has_BUFF    :
            return isWrong
        if LogMode.isReadable(self.MODE):
            self.BUFF = self.read(self.FILE)
            logSlot.GetInstance().logReadSignal(self)
            isWrong = 1
        else:
            isWrong = self.send(self.FILE, self.BUFF)
        return isWrong


    @staticmethod
    def read(fp: Qt.QFile) -> str:
        buffer: str = ''
        if not isinstance(fp, Qt.QFile) or not fp.isOpen():
            return buffer
        stream: Qt.QTextStream = Qt.QTextStream(fp)
        stream.setCodec("UTF-8")
        stream.seek(0)
        while not stream.atEnd():
            buffer += stream    .readLine()
            logUtils.processGlobalEvent(100)
        return buffer

    @staticmethod
    def send(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")
        Qt.endl(stream) << buffer
        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

    @staticmethod
    def open(fp: Qt.QFile, level: int, mode: int) -> int:
        isWrong: int
        _opened: bool = False
        if isinstance(fp, Qt.QFile):
            if fp.isOpen():
                fp.close()
            filename: str = LogLevel.filename(level)
            info: Qt.QFileInfo = Qt.QFileInfo(filename)
            if not info.dir().exists():
                info.dir().mkpath(info.absolutePath())
            fp.setFileName(info.absoluteFilePath())
            if mode == LogMode.LOG_SEND:
                _opened = fp.open(Qt.QIODevice.ReadWrite | Qt.QIODevice.Text)
            else:
                _opened = fp.open(Qt.QIODevice.ReadOnly | Qt.QIODevice.Text)
        isWrong = 1 if _opened else 0
        return isWrong

    @staticmethod
    def closeFILE(fp: Qt.QFile):
        if isinstance(fp, Qt.QFile):
            if fp.isOpen():
                fp.flush()
                fp.close()
        return

