import os
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import (
    QAction,
    QMessageBox,
    QInputDialog,
    QMenu
)
from qgis.core import (
    QgsProject,
    QgsLayoutItemMap,
    QgsRectangle
)


class MJNETWORKzoomtoextent:

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

    # --------------------------------------------------
    # INIT GUI
    # --------------------------------------------------
    def initGui(self):

        # 🔹 Icon path
        icon_path = os.path.join(os.path.dirname(__file__), "icon.png")

        # 🔹 Create Action
        self.action = QAction(
            QIcon(icon_path),
            "MJ Zoom Extent",
            self.iface.mainWindow()
        )
        self.action.setToolTip("MJNETWORK | Zoom Layout To Map Canvas Extent")
        self.action.triggered.connect(self.run_sync)

        # 🔹 Get menu bar
        menubar = self.iface.mainWindow().menuBar()

        # 🔹 Find existing MJNETWORK menu
        for menu in menubar.children():
            if isinstance(menu, QMenu) and menu.title() == "MJNETWORK":
                self.mj_menu = menu
                break

        # 🔹 If not found, create new MJNETWORK menu
        if not self.mj_menu:
            self.mj_menu = QMenu("MJNETWORK", menubar)
            menubar.addMenu(self.mj_menu)

        # 🔹 Add action to MJNETWORK menu
        self.mj_menu.addAction(self.action)

        # 🔹 Optional: Toolbar icon
        self.iface.addToolBarIcon(self.action)

    # --------------------------------------------------
    # UNLOAD
    # --------------------------------------------------
    def unload(self):
        if self.mj_menu and self.action:
            self.mj_menu.removeAction(self.action)

        if self.action:
            self.iface.removeToolBarIcon(self.action)

    # --------------------------------------------------
    # MAIN FUNCTION
    # --------------------------------------------------
    def run_sync(self):

        canvas = self.iface.mapCanvas()
        canvas_extent = canvas.extent()

        manager = QgsProject.instance().layoutManager()
        layouts = manager.layouts()

        if not layouts:
            QMessageBox.warning(None, "MJNETWORK", "Koi layout nahi mila!")
            return

        # 🔹 Select layout if more than one
        if len(layouts) == 1:
            layout = layouts[0]
        else:
            names = [layout.name() for layout in layouts]
            name, ok = QInputDialog.getItem(
                None,
                "Select Layout",
                "Layout select karein:",
                names,
                0,
                False
            )
            if not ok:
                return
            layout = manager.layoutByName(name)

        # 🔹 Get map item
        map_items = [i for i in layout.items() if isinstance(i, QgsLayoutItemMap)]
        if not map_items:
            QMessageBox.warning(None, "MJNETWORK", "Layout me map frame nahi mila!")
            return

        map_item = map_items[0]

        # --------------------------------------------------
        # FULL-FILL EXTENT LOGIC (Aspect Ratio Match)
        # --------------------------------------------------
        frame_w = map_item.rect().width()
        frame_h = map_item.rect().height()
        frame_ratio = frame_w / frame_h

        center = canvas_extent.center()
        cw = canvas_extent.width()
        ch = canvas_extent.height()
        canvas_ratio = cw / ch

        new_w, new_h = cw, ch

        if canvas_ratio > frame_ratio:
            new_h = cw / frame_ratio
        else:
            new_w = ch * frame_ratio

        new_extent = QgsRectangle(
            center.x() - new_w / 2,
            center.y() - new_h / 2,
            center.x() + new_w / 2,
            center.y() + new_h / 2
        )

        map_item.setExtent(new_extent)
        map_item.refresh()
        layout.refresh()

        self.iface.openLayoutDesigner(layout)
