# SPDX-FileCopyrightText: 2025 XLeitstelle Planen und Bauen <xleitstelle@gv.hamburg.de>
# SPDX-FileContributor: Anton Jacobsson <anton.jacobsson@init.de>
# SPDX-FileContributor: Tobias Kraft <tobias.kraft@gv.hamburg.de>
#
# SPDX-License-Identifier: EUPL-1.2
import logging
from typing import Callable

from qgis.core import QgsGeometry
from qgis.gui import QgsAdvancedDigitizingDockWidget, QgsMapCanvas, QgsMapToolCapture
from qgis.PyQt.QtCore import Qt

from xmas_plugin.util.metadata import PLUGIN_DIR_NAME

logger = logging.getLogger(PLUGIN_DIR_NAME)


class GeometryCaptureTool(QgsMapToolCapture):
    """Thin wrapper class around QgsMapTool for capturing geometries that are being digitized."""

    def __init__(
        self,
        canvas: QgsMapCanvas | None,
        cadDockWidget: QgsAdvancedDigitizingDockWidget | None,
        mode: QgsMapToolCapture.CaptureMode,
        handler: Callable[[QgsGeometry], None],
    ):
        """Initializes a `QgsMapToolCapture` and passes the captured geometry to a handler method."""
        super().__init__(canvas, cadDockWidget, mode)
        self._handler = handler

    def cadCanvasReleaseEvent(self, e) -> None:
        logger.debug(
            "cadCanvasReleaseEvent fired, currentVectorLayer: %s",
            self.currentVectorLayer(),
        )
        logger.debug("mapPointMatch: %s", e.mapPointMatch())
        super().cadCanvasReleaseEvent(e)
        logger.debug("cadCanvasReleaseEvent super() returned")

    def pointCaptured(self, point) -> None:
        logger.debug("pointCaptured called with: %s", point)

    def geometryCaptured(self, geometry: QgsGeometry) -> None:
        logger.debug("geometryCaptured called with: %s", geometry)
        self._handler(geometry)

    def keyPressEvent(self, e) -> None:
        if e.key() == Qt.Key_Escape:
            logger.debug(
                "User pressed escape to _either_ save a section object without geometry _or_ aborting."
            )
            self._handler(None)
        else:
            super().keyPressEvent(e)
