from qgis.PyQt.QtWidgets import QAction, QMessageBox, QInputDialog
from qgis.core import QgsProject

class ExtentBufferPlugin:
    def __init__(self, iface):
        self.iface = iface
        self.action = None

    def initGui(self):
        # Add to menu & toolbar
        self.action = QAction("Show Extent + Buffer (%)", self.iface.mainWindow())
        self.action.triggered.connect(self.show_extent)
        self.iface.addPluginToMenu("ExtentBuffer", self.action)
        self.iface.addToolBarIcon(self.action)

    def unload(self):
        self.iface.removePluginMenu("ExtentBuffer", self.action)
        self.iface.removeToolBarIcon(self.action)

    def show_extent(self):
        layer = self.iface.activeLayer()
        if layer is None:
            QMessageBox.warning(None, "Error", "No active layer is selected.")
            return

        extent = layer.extent()
        minX = extent.xMinimum()
        minY = extent.yMinimum()
        maxX = extent.xMaximum()
        maxY = extent.yMaximum()

        # Percentage input dialog
        percent, ok = QInputDialog.getDouble(
            None,
            "Buffer Settings",
            "Enter buffer percentage:",
            10.0, 0.0, 1000.0, 1
        )
        if not ok:
            return

        # Calculate buffer size
        width = maxX - minX
        height = maxY - minY
        buffer_x = width * (percent / 100.0)
        buffer_y = height * (percent / 100.0)

        minXb = minX - buffer_x
        minYb = minY - buffer_y
        maxXb = maxX + buffer_x
        maxYb = maxY + buffer_y

        msg_normal = (
            f"Original Extent:\n"
            f"{{{minX:.6f}, {minY:.6f}, {maxX:.6f}, {maxY:.6f}}}"
        )
        msg_buffer = (
            f"Buffered Extent (+{percent:.1f}%):\n"
            f"{{{minXb:.6f}, {minYb:.6f}, {maxXb:.6f}, {maxYb:.6f}}}"
        )

        QMessageBox.information(None, "Layer Extent", msg_normal + "\n\n" + msg_buffer)
