#!D:/IDE/anaconda3/envs/Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName：ModBusPool.py
@Description：
@Author：XSH
@Time：2025/11/11 20:02
@Department：研发部
@Copyright：©2025 乐辰生物
"""
from PyQt5 import Qt
from AppInterfaces.SingletonInterface import SingletonInterface
from AppInterfaces.ImplInterfaces import ModBusPoolInterface, ModBusImplInterface
from AppContexts.Contexts import ModBusContext, ModBusRegister
from AppCore.Levels import AxisLevel, ModBusLevel
from AppInterfaces.AppTimeLoop import AppTimeLoop
from AppUtils.AppUtils import AppUtils
class ModBusPool(Qt.QObject, ModBusPoolInterface, SingletonInterface):
    Locker: Qt.QMutex = Qt.QMutex()

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

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


    def initValue(self):
        super(ModBusPool, self).initValue()
        self.initMaxPoolLength()
        self.CurrentIndex = 0

    def initPools(self):
        from AppCore.AppImpls.ModBusImpl import ModBusImpl
        item: ModBusImplInterface
        if not self.isEmpty():
            for item in self.Managers:
                if not item:
                    self.Managers.remove(item)

        while self.length() < self.MaxPoolLength:
            item = ModBusImpl(self.Parameter.copy(), self)
            self.Managers.append(item)
            AppTimeLoop.processGlobalEvents(1000)

        while self.length() > self.MaxPoolLength:
            self.Managers.pop(0)
            AppTimeLoop.processGlobalEvents(1000)

    
    def delePools(self):
        item: ModBusImplInterface
        while not self.isEmpty():
            item = self.Managers.pop(0)
            item.Close()
            try:
                del item
                item = None
            except Exception as e:
                AppUtils.print_Exception(e)
            AppTimeLoop.processGlobalEvents(1000)

    
    def initManager(self):
        from AppSettings.AppSetting import AppSetting, AppConfig
        Lock: Qt.QReadLocker = Qt.QReadLocker(self.IOLocker)
        self.initContext()
        if not self.hasManagers:
            self.Managers = []
        if not self.hasPool():
            self.initPools()


    def deleManager(self):
        Lock: Qt.QReadLocker = Qt.QReadLocker(self.IOLocker)
        if self.hasParameter:
            self.delePools()


    def initManagers(self, **args):
        self.initManager()


    def deleManagers(self):
        self.deleManager()

    def initMaxPoolLength(self):
        from AppSettings.SystemSetting import SystemSetting, SystemConfig
        self.MaxPoolLength = SystemConfig.MODBUS_POOL_LENGTH


    def initContext(self):
        from AppSettings.AppSetting import AppSetting, AppConfig
        self.Parameter = AppConfig.Manipulator.ModBus

    @property
    def new_handler(self) -> ModBusImplInterface:
        item = ModBusImpl(self.Parameter.copy(), self)
        item.Open()
        return item