#!D:/IDE/anaconda3/envs python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName：MainFrame.py\n
 @DateTime: 2025/7/25 12:22\n
 @Author  ：xsh
"""
import sys
from PyQt5 import Qt
import asyncio
from qasync import QEventLoop, asyncSlot
from AppCore.DBModels import *
from AppSettings.Settings import *
from AppCore.Levels import *
from AppCore.Readers 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.UiViews import *
from AppBackEnd.AppScanningFlow import AppScanningFlow
from AppSettings.AppGlobalStatus import AppGlobalStatus, global_status
from AppInterfaces.SingletonInterface import SingletonInterface
class MainFrame(Qt.QWidget, UiInterface, SingletonInterface):
    Locker: Qt.QMutex = Qt.QMutex()
    Business    : AppScanningFlow       #
    DrawCamera  : DrawCameraView        #
    DrawCell    : CellFlowView          #
    Operation   : ScanOperationView     #
    OilStatus   : bool = False

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

    def __init__(self, parent: Qt.QWidget = None):
        super(MainFrame, self).__init__(parent=parent)
        self.Initialization('MainFrame', self, parent)
        self.initWidgetStyle()
        self.initWindowIcon()
        self.setWindowTitle("扫描系统")
        if not parent:
            self.move(Qt.QPoint(0, 0))


    def initConnect(self):
        super(MainFrame, self).initConnect()
        TYPE = Qt.Qt.ConnectionType(Qt.Qt.AutoConnection | Qt.Qt.UniqueConnection)
        self.DrawCamera.initCameraUiSignal()
        self.Operation.InitHardWareButton                  .clicked.connect(slot=self.SlotInitHardWareButton                  , type=TYPE)
        self.Operation.StatusOperationFrameButton          .clicked.connect(slot=self.SlotStatusOperationFrameButton          , type=TYPE)
        self.Operation.BuzzerSwitchButton                  .clicked.connect(slot=self.SlotBuzzerSwitchButton                  , type=TYPE)
        self.Operation.OilSwitchButton                     .clicked.connect(slot=self.SlotOilSwitchButton                     , type=TYPE)
        self.Operation.HitBotOperationFrameButton          .clicked.connect(slot=self.SlotHitBotOperationFrameButton          , type=TYPE)
        self.Operation.ManipulatorOperationFrameButton     .clicked.connect(slot=self.SlotManipulatorOperationFrameButton     , type=TYPE)
        self.Operation.ScanningOperationButton             .clicked.connect(slot=self.SlotScanningOperationButton             , type=TYPE)
        self.Operation.PauseScanOperationButton            .clicked.connect(slot=self.SlotPauseScanOperationButton            , type=TYPE)
        self.Operation.StopScanOperationButton             .clicked.connect(slot=self.SlotStopScanOperationButton             , type=TYPE)
        self.Operation.ClearWarningButton                  .clicked.connect(slot=self.SlotClearWarningButton                  , type=TYPE)

    @asyncSlot()
    async def SlotInitHardWareButton(self):
        if not self.hasBusiness:
            self.initBusiness()
        if not self.hasBusiness:
            return
        if not self.business.hasDevices:
            self.business.initDevices()
        if not self.business.hasDevices:
            return
        await self.business.devices.asynchrony_waitForDeviceHome()


    def SlotHitBotOperationFrameButton                (self):
        isVisible: bool = HitBotViews.GetInstance().isVisible()
        HitBotViews.GetInstance().setVisible(not isVisible)
        pass

    def SlotManipulatorOperationFrameButton               (self):
        isVisible: bool = SlideViews.GetInstance().isVisible()
        SlideViews.GetInstance().setVisible(not isVisible)


    def SlotInitCameraButton                    (self):
        if not self.hasBusiness:
            self.initBusiness()
        if not self.hasBusiness:
            return

    def SlotInitHitBotButton                    (self):
        if not self.hasBusiness:
            self.initBusiness()
        if not self.hasBusiness:
            return
        self.hitbot.Close()
        isWrong = self.business.hitbot.initHitBot()
        OperatingStatusModel.setHitBotInit(isWrong)

    def SlotClearWarningButton(self):
        if not self.hasBusiness:
            self.initBusiness()
        if not self.hasBusiness:
            return
        isWrong: int
        isBuzzer: int
        self.business.clearWarning()


    def SlotInitWebSocketButton                 (self):
        if not self.hasBusiness:
            self.initBusiness()
        if not self.hasBusiness:
            return
        isWrong : int
        isBuzzer: int
        isWrong, isBuzzer = self.business.motion.get_buzzer_switch()
        if 1 == isWrong:
            isBuzzer = 1 - isBuzzer
            self.business.motion.buzzer_switch(isBuzzer)

    def SlotStatusOperationFrameButton          (self):
        isVisible: bool = ChamberStatusView.GetInstance().isVisible()
        isVisible = not isVisible
        ChamberStatusView.GetInstance().setVisible(isVisible)
        if isVisible:
            ChamberStatusView.GetInstance().flushFrame()


    def SlotBuzzerSwitchButton                (self):
        self.initBusiness()
        if not self.hasBusiness:
            return
        if self.business.motion.get_oil_status():
            self.business.motion.oil_switch(False)
        else:
            self.business.motion.oil_switch(True)


    def SlotOilSwitchButton                (self):
        self.initBusiness()
        if not self.hasBusiness:
            self.OilStatus = False
            return
        if not self.business.hasDetection:
            self.OilStatus = False
            return
        # self.OilStatus = self.business.detection.get_oil_status()
        if self.OilStatus:
            self.OilStatus = False
        else:

            self.OilStatus = True

        self.business.detection.oil_switch(self.OilStatus)
        # if self.business.motion.get_oil_status():
        #     self.business.motion.oil_switch(False)
        #     return
        # BeginOilDropingTimes, BeginOilDropingFinishWaitTimes, BeginOilDropingSpeed = AnointingModel.getBeginOilDrippingTimeAndSpeed(ObjectiveLevel.Objective10)
        """设置油泵速度"""
        # self.business.startOilDripping(BeginOilDropingSpeed)
        """打开油泵并等待一定时长后关闭"""
        # self.business.motion.oil_switch(True)
        # self.detection.oil_switch(False)
        # self.business.oilDripping(BeginOilDropingTimes, BeginOilDropingFinishWaitTimes)


    def SlotScanningOperationButton             (self):
        self.initBusiness()
        if not self.hasBusiness:
            return
        self.business.startScanning()
        isRunning = global_status.isRunning
        self.Operation.ScanningOperationButton.setEnabled(not isRunning)
        self.business.WaitDone()
        isRunning = global_status.isRunning
        self.Operation.ScanningOperationButton.setEnabled(not isRunning)


    def SlotPauseScanOperationButton            (self):

        isPauseRunning = global_status.isPause
        global_status.setPause(not isPauseRunning)
        if isPauseRunning:
            self.Operation.PauseScanOperationButton.setText("暂停扫描　　")
        else:
            self.Operation.PauseScanOperationButton.setText("继续扫描　　")

    def SlotStopScanOperationButton             (self):
        from AppSettings.AppGlobalStatus import AppGlobalStatus, AppStatus
        AppStatus.setExit(True)

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


    def initValue(self):
        super(MainFrame, self).initValue()
        self.initBusiness    ()
        self.initDrawCamera  ()
        self.initDrawCell    ()
        self.initOperation   ()
        ChamberStatusView   .GetInstance().setVisible(False)
        SlideViews          .GetInstance().setVisible(False)
        HitBotViews         .GetInstance().setVisible(False)
        isPauseRunning = global_status.isPause
        isRunning      = global_status.isRunning
        if isPauseRunning:
            self.Operation.PauseScanOperationButton.setText("继续扫描　　")
        else:
            self.Operation.PauseScanOperationButton.setText("暂停扫描　　")
        self.Operation.ScanningOperationButton.setEnabled(not isRunning)

    def initProperty(self):
        super(MainFrame, self).initProperty()
        self.Operation.setFixedWidth(self.DrawCamera.width())



    def initLayouts(self):
        super(MainFrame, self).initLayouts()
        if self.hasWindowLayouts:
            return
        layout: Qt.QGridLayout      = Qt.QGridLayout()
        v_layout: Qt.QVBoxLayout    = Qt.QVBoxLayout()
        layout.setAlignment(Qt.Qt.AlignTop)
        layout.setSpacing(1)
        layout.setContentsMargins(2, 2, 2, 2)
        v_layout.setSpacing(1)
        v_layout.setContentsMargins(0, 0, 0, 0)

        v_layout.addWidget(self.DrawCamera  )
        v_layout.addWidget(self.Operation   )
        layout.addLayout(v_layout           , 0, 0, -1,  1)
        layout.addWidget(self.DrawCell      , 0, 1, -1, -1)
        self.setLayout(layout)
        self.initWindowIcon()

    def initDrawCamera  (self):
        if not self.hasDrawCamera  :
            self.DrawCamera   = DrawCameraView (self)

    def initDrawCell    (self):
        if not self.hasDrawCell    :
            self.DrawCell     = CellFlowView   ()

    def initOperation  (self):
        if not self.hasOperation :
            self.Operation  = ScanOperationView  (self)


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


    @property
    def hasDrawCamera     (self) -> bool:
        return hasattr(self, 'DrawCamera'     ) and isinstance(self.DrawCamera     , DrawCameraView    )

    @property
    def hasDrawCell(self) -> bool:
        return hasattr(self, 'DrawCell') and isinstance(self.DrawCell, CellFlowView)

    @property
    def hasOperation  (self) -> bool:
        return hasattr(self, 'Operation'  ) and isinstance(self.Operation  , ScanOperationView )

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

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

    @property
    def camera(self) -> CameraReader:
        return None if not self.hasCamera else self.HardWare.Camera

    @property
    def motion(self) -> MotionReader:
        return None if not self.hasMotion else self.HardWare.Motion

    @property
    def detection(self) -> MotionReader:
        return None if not self.hasMotion or not self.motion.hasDetection else self.HardWare.Motion.detection

    @property
    def hitbot(self) -> HitBotReader:
        return None if not self.hasHitBot else self.HardWare.HitBot

    @property
    def scancode(self) -> ScanCodeReader:
        return None if not self.hasScanCode else self.HardWare.scancode

    @property
    def websocket(self) -> WebReader:
        return None if not self.hasWebSocket else self.HardWare.websocket

    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()))

    def closeEvent(self, ev: Qt.QCloseEvent) -> None:
        ev.ignore()
        HeadEndShowMode['DEBUG_SHOW'] = False
        self.hide()