# -*- 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
 ***************************************************************************/

/***************************************************************************
 *                           s                                              *
 *   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 QgsProcessingException, QgsProject
from PyQt5.QtCore import QVariant
from PyQt5.QtWidgets import QMessageBox
import json
import os
from .Sewercalc_Estilo import aplicar_estilo
from .Sewercalc_Add_colunas_funcao import Add_colunas

def limpar_json(nome_arquivo):
    if os.path.exists(nome_arquivo):
        with open(nome_arquivo, 'w', encoding='utf-8') as f:
            json.dump({}, f) 
            
def Adicionar_campos_iniciais(dlg):
    camada_pv = dlg.C_PV.itemData(dlg.C_PV.currentIndex())
    camada_rede = dlg.C_REDE.itemData(dlg.C_REDE.currentIndex())
    camada_mde = dlg.C_MDE.itemData(dlg.C_REDE.currentIndex())


    layer_rede = QgsProject.instance().mapLayer(camada_rede)
    #limpar_json("tabela_pv.json")
    #limpar_json("tabela_rede.json")
    #limpar_json("pontos_criticos.json")
    
    
    #------------------VERIFICAR EXISTENCIA DE CAMADAS-------------------------------
    nao_encontradas = []
    if not camada_pv:
        nao_encontradas.append("PV")
    if not camada_rede:
        nao_encontradas.append("REDE")

    if nao_encontradas:  
        mensagem = "Camadas não encontradas: " + ", ".join(nao_encontradas)
        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Critical)
        msg_box.setWindowTitle("Erro")
        msg_box.setText(mensagem)
        msg_box.exec_()  
        return   
    
    #---------------------------CAMADA PV----------------------------------
    Add_colunas(camada_pv, [
        ("Q_PONT_INI", QVariant.Double, 10, 2),
        ("Q_PONT_FIM", QVariant.Double, 10, 2),
        ("CT", QVariant.Double, 10, 3)
    ])

    #---------------------------CAMADA REDE----------------------------------

    Add_colunas(camada_rede,[
        ("L", QVariant.Double, 10, 2),
        ("CONTRIB", QVariant.String, 50)
    ])

    #---------------------------PREENCHENDO COLUNA CONTRIBUIÇÃO----------------------------------
    idx_coluna_contrib = layer_rede.fields().indexFromName("CONTRIB")
    layer_rede.startEditing()
    for feature in layer_rede.getFeatures():
        valor_atual = feature.attribute("CONTRIB")
        if not valor_atual:
            layer_rede.changeAttributeValue(feature.id(), idx_coluna_contrib, "SIM")
    layer_rede.commitChanges()
    
    
    #------------APLICANDO ESTILO----------------
    aplicar_estilo(camada_pv, "Estilo01_PV.qml")
    aplicar_estilo(camada_rede, "Estilo01_REDE.qml")
    