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


import xml.etree.ElementTree as ET
from xml.dom import minidom
import os
from datetime import datetime

def criar_landxml(tabela_pv, tabela_rede, epsg, pasta_salvar):
    epsg = str(epsg)
    
    dados_rede = {
        "nome": "Rede - Projeto",
        "tipo": "Sanitary",
        "descricao": "Rede de esgoto sanitário"
    }

    # Cria o elemento raiz
    root = ET.Element("LandXML", version="1.2", date=datetime.now().strftime("%Y-%m-%d"))

    # CoordinateSystem
    coordinate_system = ET.SubElement(root, "CoordinateSystem")
    ET.SubElement(coordinate_system, "PlanFeature", name="Sistema de Coordenadas", desc=f"EPSG:{epsg}")

    # Units
    units = ET.SubElement(root, "Units")
    ET.SubElement(units, "Metric",
                  linearUnit="meter",
                  areaUnit="squareMeter",
                  volumeUnit="cubicMeter",
                  diameterUnit="millimeter")

    # Application
    ET.SubElement(root, "Application",
                  name="SewerCalc",
                  desc="Plugin de dimensionamento de Redes Coletoras de Esgoto",
                  manufacturer="Wanderilo Lima",
                  manufacturerURL="https://plugins.qgis.org/plugins/Plugin_Sewercalc/",
                  timeStamp=datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))

    # Conecta PVs às redes (Invert)
    for id_pv, col_pv in tabela_pv.items():
        if 'REDE' not in col_pv:
            col_pv['REDE'] = {}

        for id_rede, col_rede in tabela_rede.items():
            if col_pv["NOME"] == col_rede["PV_JUS"]:
                col_pv['REDE'][col_rede["NOME"]] = ("in", round(col_pv["CT"] - col_rede["PFJ"], 3))
            if col_pv["NOME"] == col_rede["PV_MONT"]:
                col_pv['REDE'][col_rede["NOME"]] = ("out", round(col_pv["CT"] - col_rede["PFM"], 3))

    # PipeNetwork
    pipe_networks = ET.SubElement(root, "PipeNetworks")
    pipe_network = ET.SubElement(pipe_networks, "PipeNetwork",
                                 name=dados_rede["nome"],
                                 pipeNetType=dados_rede["tipo"],
                                 desc=dados_rede["descricao"])

    # Structs (PVs)
    structs = ET.SubElement(pipe_network, "Structs")
    for id, col in tabela_pv.items():
        struct = ET.SubElement(structs, "Struct",
                               name=col["NOME"],
                               elevRim=str(col["CT"]),
                               elevSump=str(col["CF"]),
                               desc="PV TIPO I")
        
        for pipe, (flowDir, elev) in col['REDE'].items():
            ET.SubElement(struct, "Invert",
                          elev=str(elev),
                          flowDir=flowDir,
                          refPipe=pipe)
        
        ET.SubElement(struct, "Center").text = f"{col['y']} {col['x']}"
        ET.SubElement(struct, "CircStruct", diameter="0.60", material="Reinforced Concrete")

    # Pipes
    pipes = ET.SubElement(pipe_network, "Pipes")
    for id, col in tabela_rede.items():
        pipe = ET.SubElement(pipes, "Pipe",
                             name=col["NOME"],
                             refStart=col["PV_MONT"],
                             refEnd=col["PV_JUS"],
                             length=str(round(col["L"], 2)),
                             desc=f"Tubo DN {round(col['DN']*1000, 0)} mm em PVC")
        
        ET.SubElement(pipe, "CircPipe", diameter=str(col["DN"]*1000), material="PVC")
        
        # Propriedades personalizadas
        feature_custom = ET.SubElement(pipe, "Feature", code="CustomData")
        ET.SubElement(feature_custom, "Property", label="ProfundidadeInicial", value=str(col["PFM"]))
        ET.SubElement(feature_custom, "Property", label="ProfundidadeFinal", value=str(col["PFJ"]))

    
    xml_str = ET.tostring(root, encoding="utf-8")
    xml_pretty = minidom.parseString(xml_str).toprettyxml(indent="  ")

    # Salva
    caminho_arquivo = os.path.join(pasta_salvar, "rede_esgoto.xml")
    with open(caminho_arquivo, "w", encoding="utf-8") as f:
        f.write(xml_pretty)

    return caminho_arquivo