# -*- coding: utf-8 -*-
"""
/***************************************************************************
 QEsg_11Resumo
                                 A QGIS plugin
 Plugin para Calculo de redes de esgotamento sanitario
                              -------------------
        begin                : 2020-07-06
        git sha              : $Format:%H$
        copyright            : (C) 2016 by Jorge Almerio
        email                : jorgealmerio@yahoo.com.br
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 __future__ import absolute_import
from builtins import object
#from qgis.core import *
from qgis.PyQt.QtWidgets import QApplication #QMessageBox, QDialog, QDialogButtonBox ,QVBoxLayout, QCheckBox, QLabel
#from PyQt5.QtWidgets import QApplication
#from qgis.PyQt.QtGui import *
#from qgis.PyQt.QtCore import *
#from qgis.utils import *
#import os.path
#from .QEsg_00Model import *
from qgis.gui import QgsMessageBar, QgsMapLayerComboBox, QgsVertexMarker, QgsMapToolIdentify
#from .QEsg_04Estilos import *
from .QEsg_00Common import *
#import math

'''
Gera um resumo de extensão da rede por diâmetros
'''
class QEsg_11Resumo(object):
    common=QEsg_00Common()
    SETTINGS = common.SETTINGS
    #Atualiza o relatório Planilha de Resultados
    def CriaPlanResumo(self):
        layer = self.common.PegaQEsgLayer('PIPES', silent=False)
        if layer:
            proj = QgsProject.instance()
            
            app = QApplication.instance()
            # Access the clipboard
            clipboard = app.clipboard()
            
            #remove os layers com o mesmo nome do projeto
            layerExtDiam = "QEsg-Extensão por diametro"                        
            LayerLst=proj.mapLayersByName(layerExtDiam)
            for layer_to_remove in LayerLst:
                proj.removeMapLayer(layer_to_remove.id())
            
            layerName = layer.name()
            sql_query = """SELECT Diameter as 'Diametro', ST_Union(geometry) as geometry, format_number(sum(LENGTH),2) as Extensao FROM '{0:}' 
                        GROUP BY Diametro union select 'Total' as 'Diametro', geometry, format_number(sum(LENGTH),2) as Extensao FROM '{0:}'""".format(layerName)

            # Create the virtual layer
            layer = QgsVectorLayer(f"?query={sql_query}", layerExtDiam, "virtual")
            iface.setActiveLayer(layer)
            
            # Add the virtual layer to the QGIS project
            if layer.isValid():
                proj.addMapLayer(layer)
                root = proj.layerTreeRoot()
                layer_node = root.findLayer(layer.id())
                layer_node.setItemVisibilityChecked(False)               
                iface.showAttributeTable(layer)
                print("Virtual layer {} created successfully.".format(layerExtDiam))
            else:
                print(f"Virtual layer creation failed: {layer.lastError()}")

            feicoes = list(layer.getFeatures())
            n=len(feicoes)
            print(n)
            linha1=linha2=''
            for feicao in feicoes:
                diam=str(feicao['Diametro'])
                ext=str(feicao['Extensao'])
                if diam!='Total':
                    linha1+=diam+'\t'
                    linha2+=ext+'\t'

            linha1=linha1[:-1] #remove last \t character
            linha2=linha2[:-1] #remove last \t character
            clipboard.setText(linha1 + '\n' + linha2)
            msgTxt = 'Extensões por diametro copiados para o clipboard!'
            iface.messageBar().pushMessage('QEsg', msgTxt, level=Qgis.Info, duration=4)
            