# -*- 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 QgsField, QgsProject
from PyQt5.QtCore import QVariant

def Add_colunas(nome_camada, dados_col_camada):
    layer_camada = QgsProject.instance().mapLayer(nome_camada)
    
     # Iniciando a edição da camada
    layer_camada.commitChanges()
    layer_camada.startEditing()
    
    if not layer_camada:
        print(f"A camada '{nome_camada}' não foi encontrada.")
        return
    
    col_camada = []

    # Criar os campos a partir das tuplas fornecidas
    for col in dados_col_camada:
        if len(col) == 3:
            nome, tipo, comprimento = col
            precisao = 0
        elif len(col) == 4:
            nome, tipo, comprimento, precisao = col
        else:
            print("Formato inválido para as tuplas de colunas.")
            return
        
        # Cria um novo campo e adiciona à lista
        novo_campo = QgsField(nome, tipo, '', comprimento, precisao)
        col_camada.append(novo_campo)   

    # Obtendo a lista de campos existentes
    col_existente = {field.name(): field for field in layer_camada.fields()}

    

    # Adicionando as colunas à camada, se não existirem
    for field in col_camada:
        nome_coluna = field.name()
        
        # Verificar se a coluna já existe
        if nome_coluna not in col_existente:
            layer_camada.addAttribute(field)
    layer_camada.commitChanges()
    
#uso da função
'''Add_colunas("teste", [
   ("test01", QVariant.Int, 10),
    ("teste02", QVariant.String, 50),
    ("teste03", QVariant.Double, 10, 2),
])'''

