#!D:/IDE/anaconda3/envs python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName：MainWindow.py\n
 @DateTime: 2025/7/25 11:49\n
 @Author  ：xsh
"""
import os
import sys
from PyQt5 import Qt
from AppSettings.Settings import *
from AppCore.DBModels import *
from AppCore.Levels import *
from AppInterfaces.globalSlot import globalSlot, AppSlot
from utils import *
from AppInterfaces.UiInterface import UiInterface, AppUiProperty
from AppHeadEnd.UiCommons import *
from AppUtils.UiUtils import UiUtils
from AppHeadEnd.Frames.MainFrame import MainFrame
from AppInterfaces.SingletonInterface import SingletonInterface
from AppBackEnd.AppScanningFlow import AppScanningFlow
class MainWindow(Qt.QWidget, UiInterface, SingletonInterface):
    Locker: Qt.QMutex = Qt.QMutex()
    Business            : AppScanningFlow                       # 后台服务
    Main                : MainFrame                             # 调试界面
    Tray                : Qt.QSystemTrayIcon                    # 系统托盘
    Menu                : Qt.QMenu                              # 托盘菜单
    IconStartScanning   : Qt.QIcon                              # 开始扫描图标
    IconStopScanning    : Qt.QIcon                              # 停止扫描图标
    IconPauseScanning   : Qt.QIcon                              # 暂停扫描图标
    IconShowScanningUi  : Qt.QIcon                              # 显示界面图标
    IconShowDebugUi     : Qt.QIcon                              # 显示调试界面
    IconQuitScanning    : Qt.QIcon                              # 退出程序图标
    StartScanningSignal : Qt.pyqtSignal = Qt.pyqtSignal(object) # 开始扫描信号槽
    @classmethod
    def GetInstance(cls, *args, **kwargs) -> 'MainWindow':
        return super(MainWindow, cls).GetInstance(*args, **kwargs)

    def __init__(self, parent: Qt.QWidget = None):
        super(MainWindow, self).__init__(parent=parent)
        self.Initialization('MainWindow', self, parent)
        self.initWindowIcon()
        self.initWidgetStyle()

    def initValue(self):
        super(MainWindow, self).initValue()
        self.initWindowIcon         ()
        self.initMain               ()
        self.initMenu               ()
        self.initTray               ()
        self.initBusiness           ()
        self.Tray.setContextMenu(self.Menu)




    def initProperty(self):
        super(MainWindow, self).initProperty()
        self.setWindowTitle("医学显微图像扫描系统")
        HeadEndShowMode['DEBUG_SHOW'] = False
        if self.hasBusiness:
            self.business.UpdateDeviceStatus()
        self.Tray.show()
        self.setVisible(False)

    def initConnect(self):
        super(MainWindow, self).initConnect()
        TYPE: Qt.Qt.ConnectionType = Qt.Qt.ConnectionType(Qt.Qt.AutoConnection | Qt.Qt.UniqueConnection)
        self.Tray.activated.connect(slot=self.SlotTrayActivated, type=TYPE)

    def SlotStartScanningSignal(self, parameters: dict):
        print(f'{parameters} 启动扫描')
        """先判断是否暂停 如果暂停 就运行 如果不是则运行流程"""
        self.initBusiness()
        if self.hasBusiness:
            self.business.SlotStartScanningSignal(parameters)

    def closeEvent(self, ev: Qt.QCloseEvent) -> None:
        ev.ignore()
        self.hide()

    def SlotShowScanningUi    (self):
        """显示扫描界面"""
        pass

    def SlotStartScanning     (self):
        """开始扫描"""
        self.initBusiness()
        AppSlot.StartScanningSignal.emit({'isAuto': True})


    def SlotStopScanning      (self):
        """停止扫描"""
        self.initBusiness()
        self.business.status.setExit(True)

    def SlotPauseScanning     (self):
        """界停扫描"""
        self.initBusiness()
        isPause = self.business.status.isPause
        self.business.status.setPause(not isPause)
    def SlotShowDebugUi       (self):
        """调试界面巾"""
        self.initMain()
        isVisible: bool = self.Main.isVisible()
        isVisible = not isVisible
        HeadEndShowMode['DEBUG_SHOW'] = isVisible
        self.Main.setVisible(isVisible)


    def SlotQuitScanning      (self):
        """退出系统"""
        AppSlot.ApplicationSignal.emit('', '')
        if self.hasTray:
            self.Tray.hide()
        if AppSlot.Application is not None:
            AppSlot.Application.quit()

        sys.exit(0)



    def SlotTrayActivated(self, reason: Qt.QSystemTrayIcon.ActivationReason):
        pass


    def show(self) -> None:
        try:
            if not self.hasTray:
                self.initValue()
            self.Tray.show()
        except Exception as e:
            AppUtils.print_Exception(e)

    @property
    def business(self) -> AppScanningFlow:
        return None if not self.hasBusiness else self.Business

    def initMain(self):
        if not self.hasMain:
            self.Main = MainFrame          .GetInstance()
    def initTray(self):
        if not self.hasTray:
            self.initWindowIcon()
            self.Tray = Qt.QSystemTrayIcon(self)
            self.Tray.setIcon(self.WindowIcon)
            self.Tray.setToolTip("医学显微图像扫描系统")

    def initMenu(self):
        if not self.hasMenu:
            self.Menu = Qt.QMenu        (self)
            self.initIcons()
            # self.setWindowTitle("扫描系统")
            show_action : Qt.QAction = Qt.QAction(self.IconShowScanningUi , '扫描界面', self.Menu)
            scan_action : Qt.QAction = Qt.QAction(self.IconStartScanning  , '开始扫描', self.Menu)
            exit_action : Qt.QAction = Qt.QAction(self.IconStopScanning   , '停止扫描', self.Menu)
            pause_action: Qt.QAction = Qt.QAction(self.IconPauseScanning  , '暂停扫描', self.Menu)
            debug_action: Qt.QAction = Qt.QAction(self.IconShowDebugUi    , '调试界面', self.Menu)
            quit_action : Qt.QAction = Qt.QAction(self.IconQuitScanning   , '退出系统', self.Menu)
            TYPE: Qt.Qt.ConnectionType = Qt.Qt.ConnectionType(Qt.Qt.AutoConnection | Qt.Qt.UniqueConnection)
            show_action  .triggered.connect(slot=self.SlotShowScanningUi    , type=TYPE)
            scan_action  .triggered.connect(slot=self.SlotStartScanning     , type=TYPE)
            exit_action  .triggered.connect(slot=self.SlotStopScanning      , type=TYPE)
            pause_action .triggered.connect(slot=self.SlotPauseScanning     , type=TYPE)
            debug_action .triggered.connect(slot=self.SlotShowDebugUi       , type=TYPE)
            quit_action  .triggered.connect(slot=self.SlotQuitScanning      , type=TYPE)
            self.Menu.addActions([show_action  ,scan_action  ,exit_action  ,pause_action ,debug_action ,quit_action  ])


    def initBusiness(self):
        if not self.hasBusiness:
            self.Business = AppScanningFlow.GetInstance()

    def initIconStartScanning   (self):
        if not self.hasIconStartScanning   :
            info: Qt.QFileInfo = Qt.QFileInfo(f'{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Icon/start.png')
            self.IconStartScanning    = Qt.QIcon(Qt.QPixmap(info.absoluteFilePath()))

    def initIconStopScanning    (self):
        if not self.hasIconStopScanning    :
            info: Qt.QFileInfo = Qt.QFileInfo(f'{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Icon/stop.png')
            self.IconStopScanning     = Qt.QIcon(Qt.QPixmap(info.absoluteFilePath()))

    def initIconPauseScanning   (self):
        if not self.hasIconPauseScanning   :
            info: Qt.QFileInfo = Qt.QFileInfo(f'{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Icon/Pause.png')
            self.IconPauseScanning    = Qt.QIcon(Qt.QPixmap(info.absoluteFilePath()))

    def initIconShowScanningUi  (self):
        if not self.hasIconShowScanningUi  :
            info: Qt.QFileInfo = Qt.QFileInfo(f'{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Icon/show.png')
            self.IconShowScanningUi   = Qt.QIcon(Qt.QPixmap(info.absoluteFilePath()))

    def initIconShowDebugUi     (self):
        if not self.hasIconShowDebugUi     :
            info: Qt.QFileInfo = Qt.QFileInfo(f'{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Icon/debug.png')
            self.IconShowDebugUi      = Qt.QIcon(Qt.QPixmap(info.absoluteFilePath()))

    def initIconQuitScanning    (self):
        if not self.hasIconQuitScanning    :
            info: Qt.QFileInfo = Qt.QFileInfo(f'{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Icon/quit.png')
            self.IconQuitScanning     = Qt.QIcon(Qt.QPixmap(info.absoluteFilePath()))




    def initIcons(self):
        self.initIconShowScanningUi ()
        self.initIconStartScanning  ()
        self.initIconStopScanning   ()
        self.initIconPauseScanning  ()
        self.initIconShowDebugUi    ()
        self.initIconQuitScanning   ()




    def initWidgetStyle(self):
        self.setStyleSheet(UiUtils.getWidgetStyle())


    def loadWindowIcon(self):
        if not self.has_WindowIcon:
            import sys
            info: Qt.QFileInfo = Qt.QFileInfo(f'{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Icon/eraser.png')
            self.WindowIcon = Qt.QIcon(Qt.QPixmap(info.absoluteFilePath()))



    @property
    def hasMain(self) -> bool:
        return hasattr(self, 'Main') and isinstance(self.Main, MainFrame          )

    @property
    def hasTray(self) -> bool:
        return hasattr(self, 'Tray') and isinstance(self.Tray, Qt.QSystemTrayIcon )

    @property
    def hasMenu(self) -> bool:
        return hasattr(self, 'Menu') and isinstance(self.Menu, Qt.QMenu        )

    @property
    def hasBusiness(self) -> bool:
        return hasattr(self, 'Business') and isinstance(self.Business, AppScanningFlow)

    @property
    def hasIconStartScanning    (self) -> bool:
        return hasattr(self, 'IconStartScanning'  ) and isinstance(self.IconStartScanning   , Qt.QIcon)

    @property
    def hasIconStopScanning     (self) -> bool:
        return hasattr(self, 'IconStopScanning'   ) and isinstance(self.IconStopScanning    , Qt.QIcon)

    @property
    def hasIconPauseScanning    (self) -> bool:
        return hasattr(self, 'IconPauseScanning'  ) and isinstance(self.IconPauseScanning   , Qt.QIcon)

    @property
    def hasIconShowScanningUi   (self) -> bool:
        return hasattr(self, 'IconShowScanningUi' ) and isinstance(self.IconShowScanningUi  , Qt.QIcon)

    @property
    def hasIconShowDebugUi      (self) -> bool:
        return hasattr(self, 'IconShowDebugUi'    ) and isinstance(self.IconShowDebugUi     , Qt.QIcon)

    @property
    def hasIconQuitScanning     (self) -> bool:
        return hasattr(self, 'IconQuitScanning'   ) and isinstance(self.IconQuitScanning    , Qt.QIcon)

    @property
    def hasStartScanningSignal  (self) -> bool:
        return hasattr(self, 'StartScanningSignal') and isinstance(self.StartScanningSignal , Qt.QIcon)
