from qgis import processing
from processing.core.Processing import Processing

from qgis.PyQt.QtCore import (Qt, QEventLoop, QUrl)
from qgis.PyQt.QtGui import (QBrush, QColor, QIcon, QImage, QPalette, QPixmap, QMovie, QStandardItemModel)
from qgis.PyQt.QtWidgets import (QApplication, QComboBox, QDialog, QDoubleSpinBox, QFrame, QHBoxLayout, QLabel, QSpinBox, QTableView, QTextEdit)
from qgis.core import (Qgis, QgsApplication, QgsCoordinateTransform, QgsExpression, QgsFeature, QgsFeatureRequest, QgsField, QgsFields, QgsGeometry,
                       QgsLayerTreeLayer, QgsProject, QgsVectorLayer)
from qgis.gui import QgsRubberBand

from rdigc.objmaker import (funnyPushButton, progressBar)
from rdigc.utils import (bufferPlus, dicoHasKey, getAltiPoint, getGroupServices, getThemeIcon, getTransformer, jsonDateToStrDate, setObjSizes, rbcircle, windowIcon)

from os.path import (basename, dirname, exists, isfile, join, splitext)
from qgis.PyQt.QtNetwork import (QNetworkAccessManager, QNetworkRequest)
import json

from rdigc.params import APIHUBEAU

class ui_Impacts(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self)
        self.parent = parent
        self.canvas = self.parent.canvas
        self.iface = self.parent.iface
        self.manager = QNetworkAccessManager(self.iface)
        self.timezone = self.parent.timezone
        self.tableFieldsStations = self.parent.tableFieldsStations

        self.folderStyles = join(dirname(__file__), "data/styles")
        self.stationIcon = QIcon(getThemeIcon("station.png"))
        self.rubberBand = QgsRubberBand(self.canvas, Qgis.GeometryType.Polygon)
        self.rubberBand.setBrushStyle(Qt.SolidPattern)
        self.rubberBand.setColor(Qt.yellow)
        self.rubberBand.setFillColor(Qt.blue)
        self.rubberBand.setWidth(4)
        self.setupUi()
    
    def setupUi(self):
        self.setObjectName("ui_About")
        self.maxWidth, self.maxheight = 530, 460
        setObjSizes(self, self.maxWidth, self.maxheight)
        self.resize(self.maxWidth, self.maxheight) 
        windowIcon(self, "stationimpacth_off.png")
        self.setWindowTitle("%s - Représention d'impacts potentiels  ..." % self.parent.namePlugin)

        self.labelImage = QLabel(self)
        myImgPath = getThemeIcon("rdiimpacts.png")
        carIcon = QImage(myImgPath)
        self.labelImage.setPixmap(QPixmap.fromImage(carIcon))

        self.textEdit = QTextEdit(self)
        self.textEdit.setStyleSheet("QTextEdit {font: 12px 'Arial'; color: black; background: #CCC;}")
        self.textEdit.setHtml("<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
        "p, li { white-space: pre-wrap; }\n"
        "</style></head><body style=\" font-family:\'Sans Serif\'; font-size:8pt; font-weight:400; font-style:normal;\">\n"
        "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"></p>\n"
        "<p style=\"margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">"
        "<br>La hauteur d'eau ... "
        "<br>La distance d'analyse ... "
        "<br>La distance du tampon autour du cours d'eau ... "
        "<br></body></html>")
        
        self.labelListStations = QLabel(self)
        self.labelListStations.setObjectName("labelListStations")
        self.labelListStations.setText("Stations : ")
        self.labelListStations.setAlignment(Qt.AlignRight)

        self.model = QStandardItemModel()
        self.view = QTableView()
        self.view.setModel( self.model )
        self.view.horizontalHeader().setVisible(False)
        self.view.verticalHeader().setVisible(False)
        self.view.setColumnHidden(1, True)
        self.view.verticalHeader().setDefaultSectionSize(20)
        self.view.horizontalHeader().setDefaultSectionSize(500)
        self.view.setStyleSheet("QTableView {self.canvasmin-width: 400px; max-width: 500px; selection-background-color: qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5, stop: 0 #FFFFFF, stop: 1 #000000);}")
        self.view.setShowGrid(False)

        self.listStations = QComboBox(self) 
        self.listStations.setEditable(True)
        self.listStations.setEnabled(True)
        self.listStations.setObjectName("listStations")
        self.listStations.setModel(self.model)
        self.listStations.setView(self.view)

        self.zoomStation = funnyPushButton(self)
        self.zoomStation.initPushButton(45, 32, 0, 0, "zoomStation", "", "Localiser la station", True, QIcon(getThemeIcon("zoomdata.png")), 45, 32, True, False)
        
        self.busyIndicator = progressBar(self)
        self.busyIndicator.setObjectName("busyIndicator")
        self.busyIndicator.setValue(0)
        self.busyIndicator.setVisible(False)
        

        self.labelHauteur = QLabel(self)
        self.labelHauteur.setObjectName("labelHauteur")
        self.labelHauteur.setText("Hauteur : ")
        self.labelHauteur.setAlignment(Qt.AlignRight)

        self.dblSpinBoxHauteur = QDoubleSpinBox(self)
        self.dblSpinBoxHauteur.setMaximum(15.55)
        self.dblSpinBoxHauteur.setMinimum(0.10)
        self.dblSpinBoxHauteur.setValue(2.00)
        self.dblSpinBoxHauteur.setSuffix(' m')
        self.dblSpinBoxHauteur.setObjectName("dblSpinBoxHauteur")

        self.labelDistance = QLabel(self)
        self.labelDistance.setObjectName("labelDistance")
        self.labelDistance.setText("Distance : ")
        self.labelDistance.setAlignment(Qt.AlignRight)

        self.spinBoxDistance = QSpinBox(self)
        self.spinBoxDistance.setObjectName("spinBoxDistance")
        self.spinBoxDistance.setMinimum(100)
        self.spinBoxDistance.setMaximum(3500)
        self.spinBoxDistance.setValue(1500)
        self.spinBoxDistance.setSuffix(' m')
        self.spinBoxDistance.setSingleStep(50)

        self.labelDistanceBuffer = QLabel(self)
        self.labelDistanceBuffer.setObjectName("labelDistanceBuffer")
        self.labelDistanceBuffer.setText("Distance du tampon : ")
        self.labelDistanceBuffer.setAlignment(Qt.AlignRight)

        self.spinBoxDistanceBuffer = QSpinBox(self)
        self.spinBoxDistanceBuffer.setObjectName("spinBoxDistance")
        self.spinBoxDistanceBuffer.setMinimum(10)
        self.spinBoxDistanceBuffer.setMaximum(500)
        self.spinBoxDistanceBuffer.setValue(75)
        self.spinBoxDistanceBuffer.setSuffix(' m')
        self.spinBoxDistanceBuffer.setSingleStep(10)

        self.garbageButton = funnyPushButton(self)
        self.garbageButton.initPushButton(128, 128, self.width()-450,  self.height()-140, "garbageButton", "", "Effacer les analyses", True, getThemeIcon("analyzegarbage.png"), 128, 128, True, False)

        self.analyzeButton = funnyPushButton(self)
        self.analyzeButton.initPushButton(128, 128, self.width()-300,  self.height()-140, "analyzeButton", "", "Lancer l'analyse", True, getThemeIcon("analyze.png"), 128, 128, True, False)

        self.closeButton = funnyPushButton(self)
        self.closeButton.initPushButton(128, 128, self.width()-140,  self.height()-140, "closeButton", "", "Fermer", True, getThemeIcon("closeabout.png"), 128, 128, True, False)

        self.zoomStation.clicked.connect(self.localizeStation)
        self.spinBoxDistance.valueChanged.connect(self.drawCircle)
        self.garbageButton.clicked.connect(self.delAnalyze)
        self.analyzeButton.clicked.connect(self.analyze)
        self.closeButton.clicked.connect(self.close)

        self.updateListStations()
        self.getLayerTerrain()
        self.getLayerWater()

        self.setInfos(0)

        self.listStations.currentIndexChanged.connect(self.setInfos)

    def close(self):
        self.layerStations.setSubsetString("")
        self.rubberBand.reset()
        self.reject()

    def unload(self): self.layerStations.setSubsetString(""); self.rubberBand.reset()

    def setInfos(self, index):
        if self.stations != {} :
           if self.listStations.currentText() == "" : return
           idStation = self.listStations.currentText().split(" - ")[0]

           self.textEdit.setHtml("")

           seuilsRdi = self.stations[idStation]["SEUIL_RDI"]

           mapSeuils = {"SH1" : "Seuil RDI (seuil de vigilance)", "SH2" : "Seuil de 1er débordement", "SH3" : "Seuil critique"}

           infosSeuils = "" 
           if seuilsRdi != "Pas d'infos" :               
              seuilsRdi = eval(seuilsRdi)
              i = 1
              for key in seuilsRdi.keys() :
                  if key.startswith("SH"):
                     try :
                         valueSeuil = float(seuilsRdi[key])
                         if valueSeuil == -1 : valueSeuil = "Non défini"
                     except : valueSeuil = "Non défini"
                     infosSeuils+= "- %s : %s %s<br>\n" % (mapSeuils[key], valueSeuil, "m" if valueSeuil != "Non défini" else "")
                     i+= 1      
           else :
              infosSeuils = "Pas d'infos"

           #PREPA TO PARAM
           url = APIHUBEAU % (idStation, "H", 1)
           loop = QEventLoop()
           self.replyObject = self.manager.get(QNetworkRequest(QUrl(url)))
           self.replyObject.finished.connect(loop.quit)
           loop.exec_()

           denum = 1000 
           answerAsText = bytes(self.replyObject.readAll()).decode("utf-8")
           if answerAsText :
              try :
                 json_data = json.loads(answerAsText)
                 if dicoHasKey(json_data, "data") :                     
                     mesure = json_data["data"][0]["resultat_obs"]
                     dateObs = jsonDateToStrDate(json_data["data"][0]["date_obs"], "", " ", self.timezone)                
                     lastMesure = round(mesure/denum, 2)
                     mesure = "Dernière hauteur mesurée : %s m le %s\n" % (lastMesure, dateObs)
              except : mesure = "Pas de service pour cette station" 
                      
           self.textEdit.setHtml("<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
           "p, li { white-space: pre-wrap; }\n"
           "</style></head><body style=\" font-family:\'Sans Serif\'; font-size:8pt; font-weight:400; font-style:normal;\">\n"
           "<b>%s</b><br><br>"
           "<u>Seuils pour la station</u> :<br>"
           "%s"
           "<br><u>Paramètres</u> :<br>"                      
           "- La hauteur d'eau : bornes [%s - %s]"
           "<br>- La distance d'analyse : bornes [%s - %s]"
           "<br>- La distance du tampon autour du cours d'eau : bornes [%s - %s]"
           "</body></html>" % (mesure, infosSeuils, self.dblSpinBoxHauteur.minimum( ), self.dblSpinBoxHauteur.maximum(), 
                                   self.spinBoxDistance.minimum( ), self.spinBoxDistance.maximum(),
                                   self.spinBoxDistanceBuffer.minimum( ), self.spinBoxDistanceBuffer.maximum()))

           self.drawCircle(self.spinBoxDistance.value()) 
            

    def drawCircle(self, radius):
        if self.listStations.currentText() == "" : return
        idStation = self.listStations.currentText().split(" - ")[0]
                    
        self.layerStations.setSubsetString("")
        sexp = "\"{}\" = '{}'".format("CdStationH", idStation)
        self.layerStations.setSubsetString(sexp)
        for feat in self.layerStations.getFeatures(): geom = feat.geometry(); break
        if geom :
           self.rubberBand.reset()
           N = 720 
           points, geomCircle = rbcircle(self.rubberBand, geom.asPoint(), radius, N, False, True)
           if geomCircle : self.rubberBand.addGeometry(geomCircle, self.layerStations.crs())
        

    def delAnalyze(self):
        groupServices = getGroupServices(self.iface, "SERVICE ANALYSES")
        if groupServices :
           groupServices.removeAllChildren() 

    def setValueBusyIndicator(self, value):
        self.busyIndicator.setValue(value)
        self.busyIndicator.repaint()


    def analyze(self) :

        N = 720 #360 Step 0.5 pour itération des cercles
        step = 5 #10
        hauteurEau = self.dblSpinBoxHauteur.value() 
        distance = self.spinBoxDistance.value()
        distBuffer = self.spinBoxDistanceBuffer.value()

        if self.layerStations and self.layerTerrain and self.layerWater :

            self.busyIndicator.setVisible(True)

            condCrs = (self.layerStations.crs() == self.layerTerrain.crs())
            transformCrs = None
            if not condCrs : transformCrs = QgsCoordinateTransform(self.layerStations.crs(), self.layerTerrain.crs(), QgsProject(self.iface).instance()) 
            
            if self.listStations.currentText() == "" : return
            idStation = self.listStations.currentText().split(" - ")[0]
            hauteurRef = 0
            
            self.layerStations.setSubsetString("")
            sexp = "\"{}\" = '{}'".format("CdStationH", idStation)
            self.layerStations.setSubsetString(sexp)
            for feat in self.layerStations.getFeatures(): geom  =  feat.geometry(); break
         
            line, idLine = None, None
            #SELECT BY LOCATION
            result = bufferPlus(self.layerStations.id(), distance=60, output=r'TEMPORARY_OUTPUT', cond=False)
            bufferLayer = result['OUTPUT']
            result = processing.run("native:selectbylocation", { 'INPUT' : self.layerWater, 
                                                                 'INTERSECT' : bufferLayer, 
                                                                 'METHOD' : 0, 'PREDICATE' : [0] })
                                                                 
            for feat in self.layerWater.selectedFeatures() : line = feat.geometry(); idLine = feat["ID"]; break

            self.setValueBusyIndicator(10)

                
            if line :
                newPoint = line.nearestPoint(geom)
                if newPoint :
                   #0 SET MNT + HAUTEUR 
                   hauteurRef = getAltiPoint(self.layerTerrain, newPoint.asPoint(), condCrs, transformCrs) + hauteurEau
                   
                   #1) CREATE CIRCLE ON PARAM DISTANCE
                   crs = self.layerStations.crs().authid()
                   points, geomCircle = rbcircle(self.rubberBand, newPoint.asPoint(), distance, N, False, True)
                   
                   #2) CREATE TEMPORARY LAYER WITH GEOM CIRCLE
                   newFeature = QgsFeature()
                   memoLayer = QgsVectorLayer("Polygon?crs=" + crs, "Aire d'analyse (rayon : %sm)" % distance, "memory")
                   providerMemoLayer = memoLayer.dataProvider()
                   fields = QgsFields()
                   fields.append(QgsField("fid", 2, "integer", 12, 0)) #QMetaType.Type.Int
                   fields.append(QgsField("nature", 10, "String", 50, 0)) #QMetaType.Type.QString
                   providerMemoLayer.addAttributes(fields)
                   memoLayer.startEditing()               
                   
                   if geomCircle :
                      newFeature.setGeometry(geomCircle) 
                      newFeature.setAttributes([0, "Zone analysée"])
                      providerMemoLayer.addFeatures([ newFeature ])
                   
                   memoLayer.updateExtents()
                   memoLayer.commitChanges()
                   
                   mapLayer = QgsProject.instance().addMapLayer(memoLayer, False)
                   
                   #3) GET TRONCON self.layerWater (CAT 3 & 4) FROM TEMPORARY LAYER WITH GEOM CIRCLE
                   if idLine != None :
                       self.layerWater.setSubsetString("")
                       sexp = "\"{}\" = '{}'".format("ID", idLine)
                       self.layerWater.setSubsetString(sexp)
                   
                   result = processing.run("native:intersection", {'GRID_SIZE' : None,
                                                                   'INPUT' : self.layerWater,
                                                                   'INPUT_FIELDS' : [], 
                                                                   'OUTPUT' : 'TEMPORARY_OUTPUT',
                                                                   'OVERLAY' : mapLayer,
                                                                   'OVERLAY_FIELDS' : [],
                                                                   'OVERLAY_FIELDS_PREFIX' : '' })
                                                                   
                   inputLayer = result['OUTPUT']
                   inputLayer = QgsProject.instance().addMapLayer(inputLayer, False)
                   
                   #4) CREATE BUFFER GEOMETRY FROM TRONCON self.layerWater
                   result = bufferPlus(input=inputLayer.id(), distance=distBuffer, output=r'TEMPORARY_OUTPUT', cond=False)
                   bufferArea = result['OUTPUT']
                   geomBuffer = None
                   for feat in bufferArea.getFeatures() : geomBuffer = feat.geometry(); break ; 
                   QgsProject.instance().removeMapLayers([inputLayer.id(), bufferLayer.id()])

                   self.setValueBusyIndicator(25)
                   
                   #5) CLEAN CONTEXT FOR self.layerWater & TEMPORARY LAYER
                   self.layerWater.setSubsetString("")
                   mapLayer.loadNamedStyle("D:/TEMP/QGIS/L_STYLE_IMPACT.qml", True)
                   
                   newFeature = QgsFeature()
                   crs = self.layerStations.crs().authid()
                   memoLayerPoints = QgsVectorLayer("Point?crs=" + crs, "Points repérés (hauteur : %sm)" % hauteurEau, "memory")
                   providerMemoLayerPoints = memoLayerPoints.dataProvider()
                   fields = QgsFields()
                   fields.append(QgsField("fid", 2, "integer", 12, 0)) #QMetaType.Type.Int
                   fields.append(QgsField("hauteur", 6, "float", 4, 2)) #QMetaType.Type.Float
                   fields.append(QgsField("delta", 6, "float", 4, 2)) #QMetaType.Type.Float
                   providerMemoLayerPoints.addAttributes(fields)
                   memoLayerPoints.startEditing()
                   
                   fid = 0
                   
                   for i in range(0, distance, step):
                       getCircle = True if i == (distance-step) else False
                       points, geomCircle = rbcircle(self.rubberBand, newPoint.asPoint(), i, N, True, getCircle)                       
                       for key in points.keys() :
                           point = points[key]
                           hauteur = getAltiPoint(self.layerTerrain, point, condCrs, transformCrs)
                           geomPoint = QgsGeometry().fromPointXY(point)
                           if geomBuffer :
                              if hauteur < hauteurRef and geomPoint.intersects(geomBuffer) : 
                                 newFeature.setGeometry(geomPoint) 
                                 newFeature.setAttributes([fid, hauteur, (hauteurRef-hauteur)])
                                 providerMemoLayerPoints.addFeatures([ newFeature ])
                                 fid+= 1
                                 
                       self.setValueBusyIndicator(25+int(75*(i/distance)))  
                       
                   
                   memoLayerPoints.updateExtents()
                   memoLayerPoints.commitChanges()

                   self.setValueBusyIndicator(100)
                   
                   newFeature = QgsFeature()
                   crs = self.layerStations.crs().authid()
                   memoLayerArea = QgsVectorLayer("Polygon?crs=" + crs, "Zone potentiellement impactée (hauteur : %sm)" % hauteurEau, "memory")
                   providerMemoLayerArea = memoLayerArea.dataProvider()
                   fields = QgsFields()
                   fields.append(QgsField("fid", 2, "integer", 12, 0)) #QMetaType.Type.Int
                   fields.append(QgsField("nature", 10, "String", 50, 0)) #QMetaType.Type.QString
                   providerMemoLayerArea.addAttributes(fields)
                   memoLayerArea.startEditing()
                   
                   fid = 0
                   result = processing.run("native:concavehull", { 'ALPHA' : 0.050, 
                                                                   'HOLES' : False,
                                                                   'INPUT' : memoLayerPoints, 
                                                                   'NO_MULTIGEOMETRY' : False, 
                                                                   'OUTPUT' : 'TEMPORARY_OUTPUT' })
                                                                   
                                                                   
                   resultArea = result['OUTPUT']
                   geomArea = None
                   for feat in resultArea.getFeatures() : geomArea = feat.geometry().smooth(2, 0.25, 1.0, 180.0) ; break ; 
                 
                   newFeature.setGeometry(geomArea) 
                   newFeature.setAttributes([fid, "Zone potentiellement impactée"])
                   providerMemoLayerArea.addFeatures([ newFeature ])  
                   memoLayerArea.updateExtents()
                   memoLayerArea.commitChanges()
                   
                   groupServices = getGroupServices(self.iface, "SERVICE ANALYSES")
                   cond = True
                   if groupServices : 
                      groupServices.setExpanded(True)
                      groupServices.setItemVisibilityChecked(True)
                      groupServices.parent().setItemVisibilityChecked(True) 
                      cond = False
                   
                   
                   mapLayerBufferEau = QgsProject.instance().addMapLayer(bufferArea, cond)
                   #SET THE NAME FOR mapLayerBufferEau
                   mapLayerBufferEau.setName("Tampon autour du lit ( distance : %sm)" % distBuffer)
                   mapLayerPoints = QgsProject.instance().addMapLayer(memoLayerPoints, cond) 
                   mapLayerArea = QgsProject.instance().addMapLayer(memoLayerArea, cond)

                   #STYLES IN FOLDER  
                   mapLayerBufferEau.loadNamedStyle("%s/L_STYLE_IMPACT_BUFFER.qml" % self.folderStyles, True)
                   mapLayerPoints.loadNamedStyle("%s/L_STYLE_IMPACT_POINTS.qml" % self.folderStyles, True)
                   mapLayerArea.loadNamedStyle("%s/L_STYLE_IMPACT.qml" % self.folderStyles, True)
                   mapLayer.loadNamedStyle("%s/L_STYLE_AREA_ANA.qml" % self.folderStyles, True)
                   
                   if not cond :
                      nodeLayer = QgsLayerTreeLayer(mapLayer)
                      groupServices.insertChildNode(0, nodeLayer)
                      nodeLayer.setItemVisibilityChecked(True)
                      nodeLayer = QgsLayerTreeLayer(mapLayerBufferEau)
                      groupServices.insertChildNode(0, nodeLayer)
                      nodeLayer.setItemVisibilityChecked(False)
                      nodeLayer = QgsLayerTreeLayer(mapLayerPoints)
                      groupServices.insertChildNode(0, nodeLayer)
                      nodeLayer.setItemVisibilityChecked(False)
                      nodeLayer = QgsLayerTreeLayer(mapLayerArea)
                      groupServices.insertChildNode(0, nodeLayer)
                      nodeLayer.setItemVisibilityChecked(True)

                   self.busyIndicator.setVisible(False) 
                   self.setValueBusyIndicator(0) 
                   
                   self.layerWater.removeSelection()
                   self.layerStations.setSubsetString("")
        
        
        return

    def localizeStation(self):
        if self.listStations.currentText() == "" : return
        idStation = self.listStations.currentText().split(" - ")[0]

        self.layerStations.setSubsetString("")
        fieldCdStationH = self.tableFieldsStations['CdStationH']
        exp = QgsExpression(" \"{}\" = '{}' ".format(fieldCdStationH, idStation.replace("'", "''")))
        request = QgsFeatureRequest(exp)
                 
        geomType = self.layerStations.geometryType()

        for feat in self.layerStations.getFeatures(request):
            geom = feat.geometry()
            if geomType != 2 : geom = geom.buffer(self.spinBoxDistance.value()+100, 12)
            rect = geom.boundingBox()
            self.canvas.setExtent(rect)
            self.canvas.refresh()
            break        


    def getLayerStation(self):
        self.layerStations = self.parent.layerStations
        layers = QgsProject.instance().mapLayersByName(self.layerStations)
        self.layerStations = layers[0] if layers != [] else None

    def getLayerTerrain(self):
          self.layerTerrain = self.parent.layerTerrain
          layers = QgsProject.instance().mapLayersByName(self.layerTerrain)
          self.layerTerrain = layers[0] if layers != [] else None

    def getLayerWater(self):
          self.layerWater = self.parent.layerWater
          layers = QgsProject.instance().mapLayersByName(self.layerWater)
          self.layerWater = layers[0] if layers != [] else None

    def updateListStations(self):
          self.listStations.clear()
          self.getLayerStation()

          try :  
              if not self.layerStations : return
          except :
              self.parent.dialogImpacts = None
              self.close()    
          if self.tableFieldsStations == {} : return

          fieldsNames = self.layerStations.fields().names()
          mapfieldsNames = map(lambda x:x.upper(), fieldsNames)

          if  not "DtFermetur".upper() in mapfieldsNames :
              features = self.layerStations.getFeatures()
          else : 
              exp = QgsExpression(" \"{}\" = '{}' ".format("DtFermetur", '0'))
              request = QgsFeatureRequest(exp)
              features = self.layerStations.getFeatures(request)

          fieldCdStationH = self.parent.tableFieldsStations['CdStationH']
          fieldLbStationH = self.parent.tableFieldsStations['LbStationH']
          fieldCdAncieRef = self.parent.tableFieldsStations['CdAncieRef']
          fieldSeuilRDI   = self.parent.tableFieldsStations['SEUIL_RDI']
 
          try : indexRdi = self.layerStations.fields().names().index(fieldSeuilRDI) 
          except : indexRdi = -1
          stations = {}

          transformer = getTransformer(self.layerStations.crs().authid(), 4326) 
          for feat in features:
              idStation = feat[fieldCdStationH]
              seuilRdi = feat[fieldSeuilRDI] if indexRdi >-1 else "Pas d'infos"
              point = feat.geometry().centroid().asPoint()    
              pointLL = transformer.transform(point, QgsCoordinateTransform.ForwardTransform) 
              longitude = pointLL.x()
              latitude =  pointLL.y()
              stations[idStation] = {"lbStation" : feat[fieldLbStationH], "idHydro" : feat[fieldCdAncieRef], "SEUIL_RDI" : seuilRdi if seuilRdi else "Pas d'infos", "latitude" : latitude, "longitude"  : longitude} 

          self.stations = stations
          orderedStations = dict(sorted(stations.items()))

          i = 1

          for idStation in orderedStations :
              lbStation, idHydro = orderedStations[idStation]["lbStation"], orderedStations[idStation]["idHydro"] 
              self.listStations.addItem(self.stationIcon, "%s - %s" % (idStation, lbStation))
              item = self.listStations.model().item(i, 0)
              i+= 1  
        

    def resizeEvent(self, ev):
        self.labelImage.setGeometry(20, 10, 490, 360)
        
        self.labelListStations.setGeometry(5, 50, 100, 25) 
        self.listStations.setGeometry(105, 45, 340, 25)
        self.zoomStation.setGeometry(450, 45, 25, 25)

        self.busyIndicator.setGeometry(105, 75, 340, 10)
        
        self.labelHauteur.setGeometry(130, 100, 120, 25)
        self.dblSpinBoxHauteur.setGeometry(255, 95, 80, 25)
        self.labelDistance.setGeometry(130, 130, 120, 25)
        self.spinBoxDistance.setGeometry(255, 125, 80, 25)
        self.labelDistanceBuffer.setGeometry(130, 160, 120, 25)
        self.spinBoxDistanceBuffer.setGeometry(255, 155, 80, 25)

        self.textEdit.setGeometry(50, 185, 440, 165)


        
       

