#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName: DBManager.py
 @DateTime: 2025/6/22 14:52
 @SoftWare: PyCharm
 @Author  ：xsh
"""
from PyQt5 import Qt
from abc                                import abstractmethod
from AppInterfaces.SingletonInterface   import SingletonInterface
from sqlalchemy                         import Engine, create_engine
from sqlalchemy.orm import declarative_base, mapper, sessionmaker, Session
from AppUtils import AppUtils


class DBManagerInterface:
    # Engine: Engine
    @property
    def has_Engine(self) -> bool:
        return hasattr(self, 'Engine') and isinstance(self.Engine, Engine)

    @abstractmethod
    def initEngine(self):
        pass
        # if not self.has_DBEngine :
        #     self.DBEngine  = create_engine(AppSetting.GetInstance().dbConfig.get_sqlalchemy_info(),echo=False,max_overflow=20)

class DBManager(Qt.QObject, DBManagerInterface, SingletonInterface):
    Locker: Qt.QMutex = Qt.QMutex()
    @classmethod
    def GetInstance(cls, *args, **kwargs) -> 'DBManager':
        return super(DBManager, cls).GetInstance(*args, **kwargs)

    def initEngine(self):
        if not self.has_Engine :
            try:
                from AppSettings.AppSetting import AppSetting, AppConfig
                self.Engine = create_engine(AppConfig.DB.get_sqlalchemy_information(), echo=False, max_overflow=5)

            except Exception as e:
                AppUtils.print_Exception(e)
                self.Engine = None
        try:
            if self.Engine.connect() is None:
                self.Engine = None
        except Exception as e:
            AppUtils.print_Exception(e)


    def initValue(self):
        super(DBManager, self).initValue()
        self.initEngine()


    @property
    def isAvailable(self) -> bool:
        return self.has_Engine

    @classmethod
    def Session(cls) -> Session:
        try:
            handler: DBManager = cls.GetInstance()
            handler.initEngine()
            return Session(handler.Engine)
        except Exception as e:
            AppUtils.print_Exception(e)
            return None



dbController: DBManager = DBManager.GetInstance()