#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName   : WebBusinessInterface.py
@Account    : Administrator
@Time       : 2025/8/18 17:25
@Author     : xsh
@Description: 
"""
from PyQt5 import Qt
from abc import abstractmethod, abstractclassmethod, abstractstaticmethod
from AppSettings.AppGlobalStatus            import AppGlobalStatus, AppStatus
from AppInterfaces.utils                    import *
from AppSettings.utils                      import *
from AppCore.Readers                        import WebReader, AppWebSocket
from AppCore.Levels                         import *
from AppCore.DBModels                       import *
from AppCore.Contexts                       import *
from AppCore.Requests                       import *
from AppCore.Impls                          import WebSocketClient, WebSocketServer

class WebBusinessInterface(Qt.QObject, AdapterInterface):
    Manager: WebReader              #
    Handler: WebSocketClient        #

    def initManager(self):
        if not self.hasManager:
            self.Manager = WebReader.GetInstance()

    def isValid(self) -> bool:
        return self.hasHandler and self.Handler.IsOpen()

    # def Done(self, buffer: object, *args, **kwargs):
    #     self.WebSendFrame(buffer)
    #     return
    #
    # def WaitDone(self, buffer: object, *args, **kwargs) -> int:
    #     return self.WebSendFrame(buffer)

    @abstractmethod
    def Done(self, buffer: object, *args, **kwargs):
        pass

    @abstractmethod
    def WaitDone(self, buffer: object, *args, **kwargs) -> int:
        pass

    @property
    def manager(self) -> WebReader:
        return None if not self.hasManager else self.Manager

    @property
    def handler(self) -> WebSocketClient:
        return None if not self.hasHandler else self.Handler

    @property
    def isAvailable(self) -> bool:
        return self.hasHandler and self.Handler.IsOpen()



    def WebSendFrame(self, buffer: (str, bytes, bytearray, Qt.QByteArray, Request, Response)) -> int:
        isWrong: int = RECODE_FAILURE
        if self.isAvailable:
            self.manager.Transmit(buffer)
            isWrong = RECODE_SUCCEED
        else:
            self.initManager()
            self.manager.Transmit(buffer)
            isWrong = RECODE_SUCCEED

        return isWrong

    @property
    def hasManager(self) -> bool:
        return hasattr(self, 'Manager') and isinstance(self.Manager, WebReader       )

    @property
    def hasHandler(self) -> bool:
        return hasattr(self, 'Handler') and isinstance(self.Handler, WebSocketClient )
