# -*- coding: utf-8 -*-
"""
/***************************************************************************
 QEsg_01Campos
                                 A QGIS plugin
 Plugin para Calculo de redes de esgotamento sanitario
                              -------------------
        begin                : 2016-03-15
        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 QMessageBox, QDialog, QDialogButtonBox ,QVBoxLayout, QCheckBox, QLabel
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 *

class QEsg_07Tools(object):
    common=QEsg_00Common()
    SETTINGS = common.SETTINGS
    
    # Create mininum covering points Tool
    def CreateMinCovering_Points(self, mdtLyr, pipesLyr, interfLyr):
        #Check if will run only on selected pipes
        if pipesLyr.selectedFeatureCount()==0:
            feicoes=pipesLyr.getFeatures()
        else:
            resp=QMessageBox.question(None,'QEsg',QCoreApplication.translate('QEsg','Verificar apenas os trechos selecionados em {}?'.format(pipesLyr.name())),
                                      QMessageBox.Yes, QMessageBox.No)
            if resp==QMessageBox.Yes:
                feicoes=pipesLyr.selectedFeatures()
            else:
                feicoes=pipesLyr.getFeatures()
        
        #Set the resolution to use for calculate
        try:
            rstRes = min(mdtLyr.rasterUnitsPerPixelX(),mdtLyr.rasterUnitsPerPixelY())
        except AttributeError:
            # MeshLayers have no rasterUnitsPerPixelX/Y attribute
            rstRes = 0.2    
        
        canvas = iface.mapCanvas()
        interfCampos = interfLyr.fields()
        rowNumber = interfLyr.featureCount()
        interfLyr.startEditing()
        cont = 0
        identifier = QgsMapToolIdentify(iface.mapCanvas())
        campoMesh = QCoreApplication.translate('QgsMapToolIdentify','Scalar Value')
        for pipe in feicoes:
            geom = pipe.geometry()
            ext = geom.length()
            ccm = pipe['CCM']
            ccj = pipe['CCJ']
            diam_m = float(pipe['DIAMETER'])/1000
            decl = (ccm-ccj)/ext
            recMin = float(pipe['REC_MIN']) # Minimum design covering for this pipe
            recMinTr = recMin
            minFound=False
            dist=rstRes
            while dist < (ext-rstRes):
                pipeElev = ccm-dist*decl
                ptoGeom = geom.interpolate(dist)
                point = ptoGeom.asPoint()
                
                if mdtLyr.type() == mdtLyr.MeshLayer:
                    ident = identifier.identify(ptoGeom, QgsMapToolIdentify.DefaultQgsSetting, [mdtLyr], QgsMapToolIdentify.MeshLayer)[0]
                    try:                        
                        value = float(ident.mAttributes[campoMesh])
                    except (AttributeError, ValueError):
                        QgsMessageLog.logMessage('Erro encontrado no trecho:' + pipe['DC_ID'],'QEsg_MinCovering_Points', Qgis.Info)
                        value = None
                else: #Raster layer
                    value = float(mdtLyr.dataProvider().identify(point, QgsRaster.IdentifyFormatValue).results()[1])

                if value:
                    rec = value-pipeElev-diam_m
                    #print('trecho:{0} recMinTr:{1:.3f} recMin:{2:.3f} rec:{3:.3f}'.format(pipe['DC_ID'],recMinTr,recMin, rec ))
                    if  (rec < recMinTr) and (rec < recMin):
                        minFound=True
                        recMinTr = rec # Minimum found covering for this pipe
                        ptoMin = ptoGeom
                        interfTN = value                
                dist += rstRes
            
            #Create interf point
            if minFound:
                cont += 1
                QgsMessageLog.logMessage(QCoreApplication.translate('QEsg','Recobrimento ({0:.2f}) menor que o minimo  encontrado no trecho:{1}'.format(recMinTr, pipe['DC_ID'])),
                                            'QEsg_MinCovering_Points', Qgis.Info)
                feicao = QgsFeature(interfCampos)
                feicao.setGeometry(ptoMin)
                rowNumber += 1
                feicao['DC_ID'] = rowNumber
                feicao['TIPO_INT']='TN'
                feicao['CS']=interfTN
                feicao['CI']=interfTN-recMin
                interfLyr.addFeature(feicao)

                '''
                r_pto = QgsVertexMarker(canvas)
                r_pto.setCenter(ptoMin)
                r_pto.setIconSize(30)
                '''
            #for end

        if cont>0:
            iface.messageBar().pushMessage('QEsg', QCoreApplication.translate('QEsg', u'{} ponto(s) com recobrimento menor que o mínimo adicionados(s)'.format(cont)), level=Qgis.Warning, duration=0)
            interfLyr.triggerRepaint()
        else:
            iface.messageBar().pushMessage('QEsg', QCoreApplication.translate('QEsg',u'Nenhum local encontrado com recobrimento menor que o mínimo!'), level=Qgis.Info, duration=10)
            iface.vectorLayerTools().stopEditing(interfLyr)        

    # Create mininum covering points Tool
    def CreateMinCovering_Points_Tool(self):
        pipesLyr = self.common.PegaQEsgLayer('PIPES')
        if not pipesLyr:
            return False
        interfLyr = self.common.PegaQEsgLayer('INTERFERENCES')
        if not interfLyr:
            return False
        
        #Create dialog for MDT choose
        dlg = QDialog()
        dlg.setWindowTitle(QCoreApplication.translate('QEsg',u'Selecione o MDT com a elevação'))
        
        #MDT Combobox
        ml=QgsMapLayerComboBox()
        ml.setFilters( QgsMapLayerProxyModel.RasterLayer | QgsMapLayerProxyModel.MeshLayer )
        #filter out raster without info capabilities
        outList=[]
        for i in range(0,ml.count()):
            layer = ml.layer(i)
            if layer.type() != layer.MeshLayer:
                cap = layer.dataProvider().capabilities()
                if cap<6:
                    outList.append(layer)
        ml.setExceptedLayerList(outList) 
        
        #ButtonBox
        bb=QDialogButtonBox()
        bb.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        
        #layout
        layOut = QVBoxLayout()#QGridLayout()#QVBoxLayout()
        layOut.addWidget(QLabel('MDT:'))
        layOut.addWidget(ml)
        layOut.addWidget(bb)
        dlg.setLayout(layOut)        
        dlg.setMinimumWidth(300)
        
        # Signals answers
        def ok():
            dlg.close()            
            self.CreateMinCovering_Points(ml.currentLayer(), pipesLyr, interfLyr)

        def cancel():
            dlg.close()
            
        #connect to signals
        bb.accepted.connect(ok)
        bb.rejected.connect(cancel)
        
        dlg.show()