#!D:/IDE/anaconda3/envs/Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName：DaemonController.py
@Description：
@Author：XSH
@Time：2025/12/17 17:51
@Department：研发部
@Copyright：©2025 乐辰生物
"""
import sys
import asyncio
from qasync                                                 import QEventLoop, asyncSlot , QSelectorEventLoop           #
from PyQt5                                                  import Qt                               #
from AppInterfaces.utils                                    import *                                #
from AppUtils.utils                                         import *                                #
from AppCore.Levels                                         import *                                #
from AppCore.Requests                                       import *                                #
from AppInterfaces.Interfaces                               import GlobalInterface                  #
from AppSettings.SystemSetting                              import SystemConfig, SystemSetting      #

class AppDaemonController(Qt.QThread, GlobalInterface, SingletonInterface):
    Locker: Qt.QMutex = Qt.QMutex()
    Manager: asyncio.AbstractEventLoop
    @classmethod
    def GetInstance(cls, *args, **kwargs) -> 'AppDaemonController':
        return super(AppDaemonController, cls).GetInstance(*args, **kwargs)


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


    def initValue(self):
        super(AppDaemonController, self).initValue()
        self.is_async       = False      #


    def run(self) -> None:
        if self.hasManager:
            if not self.manager.is_running():
                self.manager.run_forever()


    def initManager(self):
        if not self.hasManager:
            self.Manager = QEventLoop(Qt.QApplication.instance())
            asyncio.set_event_loop(self.Manager)


    def deleManager(self):
        if self.hasManager:
            if self.manager.is_running():
                self.manager.stop()
            if not self.Manager.is_closed():
                self.Manager.close()


    def Start(self, _loop: asyncio.AbstractEventLoop = None, **args):
        self.Manager = _loop
        self.initManager()
        self.start(Qt.QThread.HighPriority)

    def Stop(self, **args):
        AppTimeLoop.processEvents(200)

        end_times: Qt.QDateTime = Qt.QDateTime.currentDateTime().addMSecs(500)
        while True:
            if Qt.QDateTime.currentDateTime() > end_times:
                break
            if not self.isRunning():
                break
            AppTimeLoop.processEvents(200)

        try:
            if self.isRunning():
                self.terminate()
        except Exception as e:
            AppUtils.print_Exception(e)


    @property
    def hasManager(self) -> bool:
        return self.has_field('Manager', asyncio.AbstractEventLoop )

    @property
    def loop(self) -> asyncio.AbstractEventLoop:
        return None if not self.hasManager else self.Manager

    @property
    def manager(self) -> asyncio.AbstractEventLoop:
        return None if not self.hasManager else self.Manager


    def setManager(self, value: asyncio.AbstractEventLoop):
        self.Manager = value



DaemonController: AppDaemonController = AppDaemonController.GetInstance()