#!D:/IDE/anaconda3/envs/Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName：CameraController.py
@Description：
@Author：XSH
@Time：2025/11/16 13:33
@Department：研发部
@Copyright：©2025 乐辰生物
"""
import sys
import os
from PyQt5                      import Qt
from AppSettings.Settings       import *
from AppInterfaces.utils        import *
from AppCore.Levels             import *
from AppUtils.UiUtils           import UiUtils
from AppInterfaces.UiInterface  import UiInterface
from AppSettings.SystemSetting import SystemConfig, SystemSetting
import numpy as np
from AppUtils.ImageUtils import ImageUtils
class CameraController(Qt.QWidget, UiInterface):
    IOLocker: Qt.QReadWriteLock = Qt.QReadWriteLock()
    CameraUiSignal: Qt.pyqtSignal = Qt.pyqtSignal(object, object)
    Image       : Qt.QImage
    Icons       : Qt.QImage
    IsCrosshair : bool

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

    def initWidgetStyle(self):
        from AppUtils.UiUtils import UiUtils
        self.setStyleSheet(UiUtils.getTransparentStyle())
    def initValue(self):
        super(CameraController, self).initValue()
        self.initImage()
        self.initIcons()
        self.IsCrosshair = False


    def initProperty(self):
        super(CameraController, self).initProperty()
        w: int
        h: int
        w, h = SystemConfig.image.DrawImageSize()
        self.IsCrosshair = SystemConfig.isDebugMode
        self.setFixedSize(w, h)

    def initConnect(self):
        super(CameraController, self).initConnect()
        TYPE: Qt.Qt.ConnectionType = Qt.Qt.ConnectionType(Qt.Qt.AutoConnection | Qt.Qt.UniqueConnection)
        AppSlot.ClearImageListSignal.connect(slot=self.SlotClearImageListSignal, type=TYPE)
        try:
            self.CameraUiSignal.connect(slot=self.SlotCameraUiSignal, type=TYPE)
        except Exception as e:
            AppUtils.print_Exception(e)

    def deleConnect(self):
        super(CameraController, self).deleConnect()
        try:
            self.CameraUiSignal.disconnect(self.SlotCameraUiSignal)
        except Exception as e:
            AppUtils.print_Exception(e)

    def SlotGlobalCameraUiSignal(self, info: object, image: object):
        img: Qt.QImage = None
        if isinstance(info, np.ndarray):
            img = ImageUtils.cv2_to_QImage(info)
        elif isinstance(info, Qt.QImage):
            img = info
        elif isinstance(image, np.ndarray):
            img = ImageUtils.cv2_to_QImage(image)
        elif isinstance(image, Qt.QImage):
            img = image
        self.SlotCameraUiSignal(img, None)

    def SlotCameraUiSignal(self, info: object, image: Qt.QImage):
        # Locker: Qt.QWriteLocker = Qt.QWriteLocker(self.IOLocker)
        if isinstance(info, Qt.QImage):
            self.Image = Qt.QImage(info)
        elif isinstance(image, Qt.QImage):
            self.Image = Qt.QImage(image)
        else:
            self.Image = None
        self.repaint()

    def SlotClearImageListSignal(self, info = None, name = None):
        self.Image = None
        self.repaint()

    def setCrosshair(self, enable: (bool, int)):
        Locker: Qt.QWriteLocker = Qt.QWriteLocker(self.IOLocker)
        self.IsCrosshair = True if isinstance(enable, (bool, int)) and enable else False

    @property
    def isCrosshair(self) -> bool:
        Locker: Qt.QReadLocker = Qt.QReadLocker(self.IOLocker)
        if not self.hasIsCrosshair:
            self.IsCrosshair = False
        return self.IsCrosshair

    @property
    def hasIsCrosshair(self) -> bool:
        return hasattr(self, 'IsCrosshair') and isinstance(self.IsCrosshair, (int, bool))

    def drawImage(self) -> Qt.QPixmap:
        src_size: Qt.QSize = self.size()
        isDraw: bool = False
        if self.hasImage:
            # 将图片缩放到适合窗口大小
            scaled_image = self.Image.scaled(src_size, Qt.Qt.IgnoreAspectRatio, Qt.Qt.SmoothTransformation)
            isDraw = True
        elif self.hasIcons:
            scaled_image = self.Icons.scaled(src_size, Qt.Qt.IgnoreAspectRatio, Qt.Qt.SmoothTransformation)
        else:
            self.initIcons()
            scaled_image = self.Icons.scaled(src_size, Qt.Qt.IgnoreAspectRatio, Qt.Qt.SmoothTransformation)
        pixmap: Qt.QPixmap = Qt.QPixmap.fromImage(scaled_image)
        painter: Qt.QPainter = Qt.QPainter(pixmap)
        if self.IsCrosshair and isDraw:
            painter.setPen(Qt.QPen(Qt.Qt.red, 2))              # 设置画笔颜色为红色，宽度为2
            painter.drawLine(0                  , 0                 , 0                 , src_size.height() )
            painter.drawLine(0                  , 0                 , src_size.width()  , 0                 )
            painter.drawLine(0                  , src_size.height() , src_size.width()  , src_size.height() )
            painter.drawLine(src_size.width()   , 0                 , src_size.width()  , src_size.height() )
            # 绘制垂直线
            painter.drawLine(src_size.width() / 2, 0, src_size.width() / 2, src_size.height())
            # 绘制水平线
            painter.drawLine(0, src_size.height() / 2, src_size.width(), src_size.height() / 2)

        return pixmap


    def paintEvent(self, ev: Qt.QPaintEvent) -> None:
        painter = Qt.QPainter(self)
        pixmap: Qt.QPixmap = self.drawImage()
        # 计算居中位置
        # 绘制图片
        painter.drawPixmap(0, 0, pixmap)
        return super(CameraController, self).paintEvent(ev)



    def initImage(self):
        if not self.hasImage:
            self.Image = Qt.QImage(f"{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Image/karyotype3.png")


    def initIcons(self):
        if not self.hasIcons:
            self.Icons = Qt.QImage(f"{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/Image/karyotype3.png")

    @property
    def hasImage(self) -> bool:
        return hasattr(self, 'Image') and isinstance(self.Image, Qt.QImage)


    @property
    def hasIcons(self) -> bool:
        return hasattr(self, 'Icons') and isinstance(self.Icons, Qt.QImage)
