#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName: AppFactory.py
 @DateTime: 2025/3/27 16:41
 @SoftWare: PyCharm
 @Author  ：xsh
"""
import sys
from PyQt5 import Qt
from AppInterfaces.SingletonInterface import SingletonInterface
from AppInterfaces.GlobalInterface import GlobalInterface
from AppUtils import AppUtils
from AppUtils.ConvertUtils import ConvertUtils
class AppFactory(Qt.QObject, GlobalInterface, SingletonInterface):
    _Handles: dict[str, str]
    _IOLocker: Qt.QReadWriteLock = Qt.QReadWriteLock()

    def __init__(self, parent: Qt.QObject = None):
        super(AppFactory, self).__init__(parent=parent)
        self.Initialization("AppFactory", self, parent)

    # def __del__(self):
    #     self.deinitialize()

    def save(self) -> bool:
        return AppUtils.save_string_to_file(self.save_filename(), self.toYaml())

    def load(self) -> bool:
        buffer: str = AppUtils.read_string_from_file(self.save_filename())
        if AppUtils.isEmpty(buffer):
            return False
        try:
            self.asYaml(buffer)
        except Exception as e:
            AppUtils.print_Exception(e)
            return False
        return True
        pass

    def asYaml(self, buffer: str):
        dict_buffer: dict[str, object] = ConvertUtils.asYaml(buffer)
        self._Handles.clear()
        for key, item in dict_buffer.items():
            self._Handles[f"{key}"] = f"{item}"

    def toYaml(self) -> dict[str, object]:
        return ConvertUtils.toYaml(self._Handles)
        pass

    def reload(self) -> bool:
        if not self.load():
            return self.save()
        return True

    def save_filename(self) -> str:
        return f"{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Settings/{self.m_Name}.yaml"
    def isValid(self) -> bool:
        return hasattr(self, '_Handles') and isinstance(self._Handles, dict)

    def initValue(self):
        super(AppFactory, self).initValue()
        self._Handles = {}

    @property
    def handles(self) -> dict[str, object]:
        return self._Handles

    def Register(self, name: str, module_name: str):
        self._Handles[name] = module_name

    def UnRegister(self, name: str):
        if name in self._Handles.keys():
            self._Handles.pop(name)

    def instance(self, name: str, isSingle: bool = False, *args, **kwargs):
        result: object = None
        if not self.isValid():
            return None
        if isinstance(name, str):
            _module_name: str = self._Handles.get(name, None)
            if isinstance(_module_name, str):
                result = AppUtils.GetModuleInstance(_module_name, name, isSingle, *args, **kwargs)
        return result

    def __getitem__(self, key: object) -> object:
        Locker: Qt.QReadLocker = Qt.QReadLocker(self._IOLocker)
        buffer: object = None
        try:
            if not self.isValid():
                self.initValue()
            if isinstance(key, str):
                _module_name: str = self._Handles.get(key, None)
                if isinstance(_module_name, str):
                   return AppUtils.GetPackageType(_module_name, key)
        except Exception as e:
            AppUtils.print_Exception(e)

        return buffer

    def __setitem__(self, key: str, value: object):
        Locker: Qt.QWriteLocker = Qt.QWriteLocker(self._IOLocker)
        try:
            if not self.isValid():
                self.initValue()
            if isinstance(key, str) and isinstance(value, str):
                self._Handles[key] = value
        except Exception as e:
            AppUtils.print_Exception(e)

    Locker: Qt.QMutex = Qt.QMutex()
    @classmethod
    def GetInstance(cls, *args, **kwargs) -> 'AppFactory':

        return super(AppFactory, cls).GetInstance(*args, **kwargs)
