# -*- coding: utf-8 -*-
"""Tool 5: Automatic A4 landscape map layout for the classified map."""

from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QFont
from qgis.PyQt.QtWidgets import QInputDialog
from qgis.core import (
    QgsProject, QgsPrintLayout, QgsLayoutItemMap, QgsLayoutItemLabel,
    QgsLayoutItemScaleBar, QgsLayoutItemShape, QgsLayoutPoint, QgsLayoutSize,
    QgsUnitTypes, QgsFillSymbol, QgsLayoutItemPage,
)

from . import gee_utils as gu


def make_layout(iface, state):
    title, ok = QInputDialog.getText(
        iface.mainWindow(), "Map layout", "Map title:",
        text="Land Use / Land Cover Classification - {}".format(
            state.get("aoi_name", "Study Area")))
    if not ok:
        return

    project = QgsProject.instance()
    manager = project.layoutManager()
    name = "LULC Map"
    i = 1
    while manager.layoutByName(name):
        i += 1
        name = "LULC Map {}".format(i)

    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName(name)
    page = layout.pageCollection().page(0)
    page.setPageSize("A4", QgsLayoutItemPage.Orientation.Landscape)

    # ---- map item (uses current canvas view)
    m = QgsLayoutItemMap(layout)
    m.attemptMove(QgsLayoutPoint(8, 22, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
    m.attemptResize(QgsLayoutSize(220, 165, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
    m.setExtent(iface.mapCanvas().extent())
    m.setFrameEnabled(True)
    layout.addLayoutItem(m)

    # ---- title
    t = QgsLayoutItemLabel(layout)
    t.setText(title)
    t.setFont(QFont("Arial", 18, QFont.Weight.Bold))
    t.adjustSizeToText()
    t.attemptMove(QgsLayoutPoint(8, 6, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
    layout.addLayoutItem(t)

    # ---- legend (manual swatches, works with GEE tile layers)
    lx, ly = 234, 22
    head = QgsLayoutItemLabel(layout)
    head.setText("Legend")
    head.setFont(QFont("Arial", 12, QFont.Weight.Bold))
    head.adjustSizeToText()
    head.attemptMove(QgsLayoutPoint(lx, ly, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
    layout.addLayoutItem(head)
    y = ly + 8
    for code, cname, color in gu.LULC_CLASSES:
        sw = QgsLayoutItemShape(layout)
        sw.setShapeType(QgsLayoutItemShape.Shape.Rectangle)
        sw.setSymbol(QgsFillSymbol.createSimple(
            {"color": color, "outline_color": "black",
             "outline_width": "0.2"}))
        sw.attemptMove(QgsLayoutPoint(lx, y, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
        sw.attemptResize(QgsLayoutSize(7, 5, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
        layout.addLayoutItem(sw)
        lab = QgsLayoutItemLabel(layout)
        lab.setText(cname)
        lab.setFont(QFont("Arial", 10))
        lab.adjustSizeToText()
        lab.attemptMove(QgsLayoutPoint(
            lx + 9, y + 0.5, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
        layout.addLayoutItem(lab)
        y += 8

    # ---- north arrow (simple)
    n = QgsLayoutItemLabel(layout)
    n.setText("▲\nN")
    n.setFont(QFont("Arial", 16, QFont.Weight.Bold))
    n.setHAlign(Qt.AlignmentFlag.AlignHCenter)
    n.adjustSizeToText()
    n.attemptMove(QgsLayoutPoint(lx + 20, y + 6,
                                 QgsUnitTypes.LayoutUnit.LayoutMillimeters))
    layout.addLayoutItem(n)

    # ---- scale bar
    sb = QgsLayoutItemScaleBar(layout)
    sb.setStyle("Single Box")
    sb.setLinkedMap(m)
    sb.applyDefaultSize()
    sb.attemptMove(QgsLayoutPoint(8, 190, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
    layout.addLayoutItem(sb)

    # ---- credits
    c = QgsLayoutItemLabel(layout)
    c.setText("Data: Google Earth Engine (Sentinel / Landsat)  |  "
              "Method: Random Forest  |  "
              "YOUR INSTITUTION NAME")
    c.setFont(QFont("Arial", 8))
    c.adjustSizeToText()
    c.attemptMove(QgsLayoutPoint(8, 200, QgsUnitTypes.LayoutUnit.LayoutMillimeters))
    layout.addLayoutItem(c)

    manager.addLayout(layout)
    iface.openLayoutDesigner(layout)
