from __future__ import annotations

from PySide6.QtCore import QTimer, Qt
from PySide6.QtGui import QKeyEvent, QPixmap, QWheelEvent
from PySide6.QtWidgets import QDialog, QGraphicsScene, QGraphicsView, QVBoxLayout


class ZoomView(QGraphicsView):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
        self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)

    def wheelEvent(self, event: QWheelEvent) -> None:
        dy = event.angleDelta().y()
        if dy == 0:
            event.ignore()
            return
        factor = 1.25 if dy > 0 else 0.8
        self.scale(factor, factor)
        event.accept()


class ImageViewerDialog(QDialog):
    def __init__(self, pixmap: QPixmap, title: str, parent=None) -> None:
        super().__init__(parent)
        self.setWindowTitle(title)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        self._view = ZoomView(self)
        self._scene = QGraphicsScene(self)
        self._view.setScene(self._scene)
        layout.addWidget(self._view)

        self._item = self._scene.addPixmap(pixmap)
        self._scene.setSceneRect(self._item.boundingRect())

        QTimer.singleShot(0, self._fit)

    def _fit(self) -> None:
        self._view.fitInView(self._item, Qt.AspectRatioMode.KeepAspectRatio)

    def keyPressEvent(self, event: QKeyEvent) -> None:
        if event.key() == Qt.Key.Key_Escape:
            self.close()
            return
        super().keyPressEvent(event)
