# -*- 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.PyQt.QtWidgets import QMessageBox
from PyQt5.QtCore import QVariant
from qgis.core import QgsProject,QgsVectorLayer, QgsFeature
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 msg_box(title, message):
        msg_box = QMessageBox()
        msg_box.setWindowTitle(title)
        msg_box.setText(message)
        msg_box.exec_()

# Função para identificar ponta seca, atualizar a coluna CAT e definir valores
def atualizar_coluna_cat():
    configuracoes = carregar_configuracoes()
    camada_pv = configuracoes.get("camada_pv") 
    camada_rede = configuracoes.get("camada_rede")

    Add_colunas(camada_pv, [("CAT", QVariant.String, 50)])
    
    layer_rede = QgsProject.instance().mapLayer(camada_rede)
    layer_pv = QgsProject.instance().mapLayer(camada_pv)

    pontos_finais = set()
    
    # Preencher o conjunto com as coordenadas dos pontos finais
    for feat in layer_rede.getFeatures():
        geom = feat.geometry()
        if geom.isMultipart():
            linhas = geom.asMultiPolyline()
        else:
            linhas = [geom.asPolyline()]

        for linha in linhas:
            if linha:  
                ponto_final = linha[-1] 
                pontos_finais.add((ponto_final.x(), ponto_final.y())) 
    
    # Criar um dicionário para rastrear os pontos iniciais ponta seca
    pontos_ponta_seca = set()

    for feat in layer_rede.getFeatures():
        geom = feat.geometry()
        if geom.isMultipart():
            linhas = geom.asMultiPolyline()
        else:
            linhas = [geom.asPolyline()]

        for linha in linhas:
            if linha:  
                ponto_inicial = linha[0]  
                if (ponto_inicial.x(), ponto_inicial.y()) not in pontos_finais:
                    pontos_ponta_seca.add((ponto_inicial.x(), ponto_inicial.y()))  
    
    # Atualizar a coluna CAT na camada PV
    layer_pv.startEditing()  
    for pv_feat in layer_pv.getFeatures():
        pv_geom = pv_feat.geometry()
        pv_point = pv_geom.asPoint()
        if (pv_point.x(), pv_point.y()) in pontos_ponta_seca:
            pv_feat["CAT"] = "PS"  
        else:
            pv_feat["CAT"] = "PV"  
        layer_pv.updateFeature(pv_feat)  

    layer_pv.commitChanges() 
    aplicar_estilo(camada_pv, "Estilo02_PV.qml")
    