#!D:/IDE/anaconda3/envs/Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName：AppTaskController.py
@Description：
@Author：XSH
@Time：2025/11/21 16:35
@Department：研发部
@Copyright：©2025 乐辰生物
"""

from PyQt5                                                  import Qt
from AppInterfaces.utils                                    import *
from AppUtils.utils                                         import *
from AppCore.Levels                                         import *
from AppCore.Requests                                       import *
from AppInterfaces.EventInterfaces                          import AppEventInterface


class AppTaskController(Qt.QThread, SingletonInterface):
    Locker: Qt.QMutex = Qt.QMutex()
    _args       : tuple                                      #
    _kwargs     : dict                                       #
    _callback   : object                                     #
    _result     : object                                     #
    _running    : bool                                       #
    @classmethod
    def GetInstance(cls, *args, **kwargs) -> 'AppTaskController':
        return super(AppTaskController, cls).GetInstance(*args, **kwargs)

    def __init__(self, target = None,args = None,kwargs = None, result = None , parent: Qt.QObject = None):
        super(AppTaskController, self).__init__(parent=parent)
        self.initValue(target, args, kwargs, result)

    def Start(self, target = None,args = None,kwargs = None, result = None ):
        if self.isRunning():
            return
        self._running = False
        self.initValue(target, args, kwargs, result)
        self.start(Qt.QThread.HighPriority)
        return self.waitForRunning()


    def initValue(self, target = None,args = None,kwargs = None, result = None ):
        try:
            self._callback = target
            self._args     = args
            self._kwargs   = kwargs
            self._result   = result
        except Exception as e:
            self._callback = None
            self._args     = None
            self._kwargs   = None
            self._result   = None
            AppUtils.print_Exception(e)

    def run(self) -> None:
        if self.has_callback:
            self._running = True
            try:
                if self.has_args:
                    if self.has_kwargs:
                        self._result = self._callback(*self.args, **self._kwargs)
                    else:
                        self._result = self._callback(*self.args)
                else:
                    if self.has_kwargs:
                        self._result = self._callback(**self._kwargs)
                    else:
                        self._result = self._callback()
            except Exception as e:
                AppUtils.print_Exception(e)
            self._running = False
        return

    def waitForFinishing(self) -> bool:
        while self.running:
            AppTimeLoop.processGlobalEvents(1000)
        return self.isRunning()


    def waitForRunning(self) -> bool:
        while not self.running:
            AppTimeLoop.processGlobalEvents(1000)
        return self.isRunning()


    @property
    def args     (self) -> tuple    :
        return None if not self.has_args      else self._args                   #

    @property
    def kwargs   (self) -> dict     :
        return None if not self.has_kwargs    else self._kwargs                 #

    @property
    def callback (self) -> object   :
        return None if not self.has_callback  else self._callback               #

    @property
    def result   (self) -> object   :
        return None if not self.has_result    else self._result                 #

    @property
    def running  (self) -> bool     :
        return None if not self.has_running   else self._running                #


    @property
    def has_args       (self) -> bool:
        return hasattr(self, '_args'    ) and isinstance(self._args       , (list, tuple)   )#

    @property
    def has_kwargs     (self) -> bool:
        return hasattr(self, '_kwargs'  ) and isinstance(self._kwargs     , dict            )#

    @property
    def has_callback   (self) -> bool:
        return hasattr(self, '_callback') and self._callback    is not None                  #

    @property
    def has_result     (self) -> bool:
        return hasattr(self, '_result'  ) and self._result      is not None                  #

    @property
    def has_running    (self) -> bool:
        return hasattr(self, '_running' ) and isinstance(self._running    , bool            )#
