# -*- coding: utf-8 -*-
"""
/***************************************************************************
 Sewercalc
                                 A QGIS plugin
 Plugin para dimensionamento de redes coletoras de esgoto 
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-02-07
        git sha              : $Format:%H$
        copyright            : (C) 2025 by Wanderilo  Lima
        email                : Wanderilo Lima
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""


from qgis.core import QgsProject, QgsGeometry, QgsWkbTypes, QgsPointXY
from qgis.PyQt.QtWidgets import QMessageBox
from PyQt5.QtCore import QVariant
from qgis.utils import iface
from .Sewercalc_Add_colunas_funcao import Add_colunas
from .Sewercalc_Estilo import aplicar_estilo
from .Sewercalc_config_cx_txt import carregar_configuracoes
import json

def adicionar_pvs_trechos():
    configuracoes = carregar_configuracoes()

    camada_pv = configuracoes.get("camada_pv") 
    camada_rede = configuracoes.get("camada_rede")
    
    def msg_box(title, message):
        msg_box = QMessageBox()
        msg_box.setWindowTitle(title)
        msg_box.setText(message)
        msg_box.exec_()
    
    Add_colunas(camada_rede, [ 
        ("PV_MONT", QVariant.String, 50),
        ("PV_JUS", QVariant.String, 50)
    ])
    
    layer_rede = QgsProject.instance().mapLayer(camada_rede)
    layer_pv = QgsProject.instance().mapLayer(camada_pv)
    
    campos = [field.name() for field in layer_pv.fields()]
    if 'NOME' not in campos:
        msg_box("ERRO AO PREENCHER", "A camada PV não possui o campo 'NOME', é necessário executar a função 'RENOMEAR TRECHOS'")
        return
    
    layer_rede.startEditing()

    for trecho in layer_rede.getFeatures():
        trecho_geom = trecho.geometry()
        tipo_geom = QgsWkbTypes.displayString(trecho_geom.wkbType())

        # Verifica se é uma geometria de linha (inclui Z, M, ZM)
        if QgsWkbTypes.geometryType(trecho_geom.wkbType()) == QgsWkbTypes.LineGeometry:
            try:
                if trecho_geom.isMultipart():
                    # Extrai linhas ignorando Z/M
                    multi_line = trecho_geom.constGet()
                    vertices = [QgsPointXY(pt.x(), pt.y()) for linha in multi_line.parts() for pt in linha]
                else:
                    # Geometria simples, ignora Z/M também
                    linha = trecho_geom.constGet()
                    vertices = [QgsPointXY(pt.x(), pt.y()) for pt in linha]
            except Exception as e:
                layer_rede.removeSelection()
                layer_rede.select(trecho.id())
                iface.mapCanvas().zoomToSelected(layer_rede)
                raise RuntimeError(f"Erro ao processar geometria do trecho {trecho.id()} (tipo: {tipo_geom})")
        else:
            layer_rede.removeSelection()
            layer_rede.select(trecho.id())
            iface.mapCanvas().zoomToSelected(layer_rede)
            raise RuntimeError(f"Tipo de geometria não suportado para o trecho {trecho.id()} (tipo: {tipo_geom})")

        if len(vertices) < 2:
            print(f"Trecho sem vértices suficientes: {trecho.id()}")
            continue

        ponto_inicial = vertices[0]
        ponto_final = vertices[-1]

        nome_pv_inicial = None
        nome_pv_final = None

        for pv in layer_pv.getFeatures():
            pv_geom = pv.geometry()
            
            if pv_geom.contains(QgsGeometry.fromPointXY(ponto_inicial)):
                nome_pv_inicial = pv["NOME"]
            if pv_geom.contains(QgsGeometry.fromPointXY(ponto_final)):
                nome_pv_final = pv["NOME"]

        trecho.setAttribute('PV_MONT', nome_pv_inicial)
        trecho.setAttribute('PV_JUS', nome_pv_final)
        layer_rede.updateFeature(trecho)

    layer_rede.commitChanges()
    aplicar_estilo(camada_rede, "Estilo02_REDE.qml")

