from PyQt6.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsPixmapItem
from PyQt6.QtGui import QPixmap, QImage
from PyQt6.QtCore import Qt, QRectF


class FrameView(QGraphicsView):
    def __init__(self):
        super().__init__()

        # << -- Setup -- >>
        self.setStyleSheet("border: none;")
        self._scene = QGraphicsScene(self)
        self._pixmap = QGraphicsPixmapItem()
        self._scene.addItem(self._pixmap)
        self.setScene(self._scene)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.setViewportUpdateMode(self.ViewportUpdateMode.FullViewportUpdate)
        self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorViewCenter)


    def resizeEvent(self, event):
        """Override the resize event to fit the view to the scene rect."""
        super().resizeEvent(event)
        if self.scene and not self.scene.sceneRect().isNull():
            self.fitInView(self.sceneRect(), Qt.AspectRatioMode.KeepAspectRatio)


    def set_image(self, image: QImage) -> None:
        """Set the image to be displayed in the view."""
        pixmap = QPixmap.fromImage(image)
        self._pixmap.setPixmap(pixmap)
        self._scene.setSceneRect(QRectF(self._pixmap.pixmap().rect())) 
        self.fitInView(self._scene.sceneRect(), Qt.AspectRatioMode.KeepAspectRatio) 
        
    @property
    def pixmap(self):
        """Return the current pixmap."""
        return self._pixmap.pixmap()
    
    @property
    def scene(self):
        """Return the current scene."""
        return self._scene