from PyQt5.QtWidgets import QAction, QMessageBox, QFileDialog
from PyQt5.QtGui import QIcon
from qgis.gui import QgsMapTool
from qgis.core import QgsProject, QgsRectangle, QgsWkbTypes
import webbrowser
import os
from . import resources_rc  # Supondo que exista seu arquivo de recursos

class PseudoHyperlink:
    def __init__(self, iface):
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.tool = None

    def initGui(self):
        # Botão para abrir links no mapa
        self.action_open_links = QAction(QIcon(":/icon.png"), "Pseudo Hyperlink - Abrir Links", self.iface.mainWindow())
        self.action_open_links.triggered.connect(self.activate_tool)
        self.iface.addPluginToMenu("&Pseudo Hyperlink", self.action_open_links)
        self.iface.addToolBarIcon(self.action_open_links)

        # Botão para exportar HTML com links
        self.action_export_html = QAction(QIcon(":/icon.png"), "Exportar HTML com Links", self.iface.mainWindow())
        self.action_export_html.triggered.connect(self.export_html_with_links)
        self.iface.addPluginToMenu("&Pseudo Hyperlink", self.action_export_html)
        self.iface.addToolBarIcon(self.action_export_html)

    def unload(self):
        self.iface.removePluginMenu("&Pseudo Hyperlink", self.action_open_links)
        self.iface.removeToolBarIcon(self.action_open_links)
        self.iface.removePluginMenu("&Pseudo Hyperlink", self.action_export_html)
        self.iface.removeToolBarIcon(self.action_export_html)

    def activate_tool(self):
        layer = self.iface.activeLayer()
        if not layer:
            QMessageBox.warning(None, "Erro", "Selecione uma camada vetorial ativa.")
            return

        self.tool = HyperlinkTool(self.canvas, layer)
        self.canvas.setMapTool(self.tool)

    def export_html_with_links(self):
        path, _ = QFileDialog.getSaveFileName(None, "Salvar HTML", "", "HTML (*.html)")
        if not path:
            return

        # Pegar apenas as camadas visíveis no painel de camadas
        layer_tree = QgsProject.instance().layerTreeRoot()
        layers = [
            node.layer()
            for node in layer_tree.findLayers()
            if node.isVisible() and node.layer() is not None
        ]

        if not layers:
            QMessageBox.warning(None, "Erro", "Nenhuma camada visível encontrada.")
            return

        html_content = """
<!DOCTYPE html>
<html lang="pt">
<head><meta charset="UTF-8"><title>Mapa com Links</title></head>
<body>
<h1>Links das Feições Visíveis</h1>
"""

        for layer in layers:
            if not layer.isValid() or layer.type() != layer.VectorLayer:
                continue  # só vetorial

            html_content += f"<h2>Camada: {layer.name()}</h2><ul>"

            for feat in layer.getFeatures():
                # Verificar campo 'link'
                if "link" not in feat.fields().names():
                    continue

                url = feat["link"]
                if not url:
                    continue

                geom = feat.geometry()
                if not geom:
                    continue

                # Obter ponto representativo para mostrar posição (como texto simples)
                rep_point = None
                if geom.type() == QgsWkbTypes.PointGeometry:
                    rep_point = geom.asPoint()
                elif geom.type() == QgsWkbTypes.LineGeometry:
                    rep_point = geom.lineString().pointN(0)
                elif geom.type() == QgsWkbTypes.PolygonGeometry:
                    rep_point = geom.centroid().asPoint()

                coord_text = ""
                if rep_point:
                    coord_text = f" ({rep_point.x():.5f}, {rep_point.y():.5f})"

                # Criar link clicável
                safe_url = url.replace('"', "&quot;")
                html_content += f'<li><a href="{safe_url}" target="_blank">{url}</a>{coord_text}</li>'

            html_content += "</ul>"

        html_content += """
</body>
</html>
"""

        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(html_content)
            QMessageBox.information(None, "Sucesso", f"Arquivo HTML salvo em:\n{path}")
        except Exception as e:
            QMessageBox.critical(None, "Erro ao salvar HTML", str(e))


class HyperlinkTool(QgsMapTool):
    def __init__(self, canvas, layer):
        super().__init__(canvas)
        self.canvas = canvas
        self.layer = layer

    def canvasReleaseEvent(self, event):
        # Obtem o ponto clicado no mapa
        point = self.canvas.getCoordinateTransform().toMapCoordinates(event.pos().x(), event.pos().y())

        # Cria uma área de busca pequena em torno do clique
        search_rect = QgsRectangle(point.x() - 0.0001, point.y() - 0.0001,
                                   point.x() + 0.0001, point.y() + 0.0001)

        # Busca feições dentro da área
        self.layer.selectByRect(search_rect)
        features = self.layer.selectedFeatures()

        if not features:
            QMessageBox.information(None, "Nenhuma feição", "Nenhuma feição encontrada nesse ponto.")
            return

        feature = features[0]  # pega a primeira feição encontrada

        if "link" not in feature.fields().names():
            QMessageBox.warning(None, "Campo ausente", "A feição não possui o campo 'link'.")
            return

        url = feature["link"]

        if url.startswith("http"):
            webbrowser.open(url)
        elif url.endswith(".pdf"):
            webbrowser.open("file://" + os.path.abspath(url))
        else:
            QMessageBox.information(None, "Link", f"Link: {url}")

        self.layer.removeSelection()

