# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ARPAdata
                                 A QGIS plugin
 This plugin downloads the data from ARPA Lombardia API
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2021-03-15
        git sha              : $Format:%H$
        copyright            : (C) 2021 by Mathilde Puche
        email                : mathilde-puche@hotmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, QVariant, QDateTime, QTime, QDate
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QApplication, QFileDialog
from qgis.core import Qgis, QgsProject, QgsVectorLayer, QgsJsonUtils, QgsFields, QgsFeature, QgsField, QgsGeometry,QgsPoint, QgsPointXY, QgsFeatureRequest, QGis

import datetime
"""import pandas as pd"""
import statistics
import json
from sodapy import Socrata


# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .arpa_data_dialog import ARPAdataDialog
import os.path


class ARPAdata:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'ARPAdata_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&ARPA data')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('ARPAdata', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/arpa_data/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'ARPA Lombardia Data Extractor'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&ARPA data'),
                action)
            self.iface.removeToolBarIcon(action)

    def connect_ARPI_api(self):
        # Unauthenticated client only works with public data sets. Note 'None'
        # in place of application token, and no username or password:
        client = Socrata("www.dati.lombardia.it", None)
        
        # Authenticated client (needed for non-public datasets):
        # client = Socrata(www.dati.lombardia.it,
        #                  MyAppToken,
        #                  userame="user@example.com",
        #                  password="AFakePassword")

        return client
    
    
    #Modify the min and max dateTime proposed to the user and the sensor type list depending on the selected dataset
    def on_dataset_changed(self, value_dataset):
        
        self.dlg.sensor_type_list.clear()
      
        if value_dataset ==1 or value_dataset ==2:
            
            #get the current time to define the available data at current time
            now_date = QDateTime.currentDateTime().date()
            now_day=now_date.day()
            if now_day < 8:
                max_date=now_date.addDays(-now_day)
            else:
                max_date=now_date.addDays(-1)
            now_month=max_date.month() #We take the max_date and not the now_date in case the date is the first day of the month
            now_year=max_date.year()
            
            if value_dataset ==1:
              
                #For weather, only the data of the current month is available
                min_datetime=QDateTime(QDate(now_year, now_month,1),QTime(1, 0, 0, 0))
                max_datetime=QDateTime(max_date, QTime(0, 0, 0, 0))
                
                #Sensor list for Weather
                items = ["Altezza Neve","Direzione Vento","Livello Idrometrico","Precipitazione", "Radiazione Globale", "Temperatura", 
                         "Umidità Relativa","Velocità Vento"]
                
            
            elif value_dataset ==2:
                
                #For the air quality, the data of the current year is available
                min_datetime=QDateTime(QDate(now_year, 1,1), QTime(0, 0, 0, 0))
                max_datetime=QDateTime(max_date, QTime(0, 0, 0, 0))
                
                #Sensor list for Air Quality
                items = ["Ammoniaca","Arsenico","Benzene","Benzo(a)pirene","Biossido di Azoto", "Biossido di Zolfo", 
                                           "BlackCarbon","Cadmio", "Monossido di Azoto", "Monossido di Carbonio", "Nikel", "Ossidi di Azoto", 
                                           "Ozono", "Particelle sospese PM2.5","Particolato Totale Sospeso", "Piombo", "PM10", "PM10 (SM2005)"]
                

            
            self.dlg.dateTime_stop.setMinimumDateTime(min_datetime)
            self.dlg.dateTime_stop.setMaximumDateTime(max_datetime)
            self.dlg.dateTime_stop.setDateTime(max_datetime)
            
            
            self.dlg.dateTime_start.setMinimumDateTime(min_datetime)
            self.dlg.dateTime_start.setMaximumDateTime(max_datetime)
            self.dlg.dateTime_start.setDateTime(min_datetime)
            
            self.dlg.sensor_type_list.addItems(items)
            
        elif value_dataset <=0:
            print("Initial value OK")
            pass
        else:
            print("No valid value for dataset number")
            pass
            

    #Modify the list selection when the user check or uncheck the checkbox for all sensors
    def on_check_changed(self, is_checked):
        if is_checked:
            self.dlg.sensor_type_list.selectAll()
        else:
            self.dlg.sensor_type_list.clearSelection()
            
            
    #Modify the checkbox for no_distinction: make it checkable if the week_days and weekends are checked
    def on_check_day_changed(self, week_days, weekends):
        if week_days and weekends:
            self.dlg.no_distinction.setCheckable(True)
            self.dlg.no_distinction.setChecked(True)
            
        else:
            self.dlg.no_distinction.setChecked(False)
            self.dlg.no_distinction.setCheckable(False)

    
    #Modify the insert line for polygon depending on the choice of the user about the area (all lombardia or insert area)
    def on_area_changed(self, area):
        if area=="Insert area":
            self.dlg.province_list.clear()
            self.dlg.province_list.setEnabled(False)
            self.dlg.line_polygon.setEnabled(True)
            self.dlg.search_button.setEnabled(True)
        elif area == "Lombardia":
            self.dlg.province_list.setEnabled(True)
            self.dlg.province_list.clear()
            self.dlg.province_list.addItems(["All provinces","BG - Bergamo", "BS - Brescia", "CO - Como", "CR - Cremona", "LC - Lecco", 
                                         "LO - Lodi", "MN - Mantova", "MI - Milano", "MB - Monza e della Brianza", "PV - Pavia", 
                                         "SO - Sondrio", "VA - Varese"])
            self.dlg.line_polygon.setEnabled(False)
            self.dlg.search_button.setEnabled(False)



    #Desable/Enable the time filters depending on the check/uncheck of the without data button
    def on_without_data_changed (self, without_data):
        if without_data:
            self.dlg.dateTime_stop.setEnabled(False)
            self.dlg.dateTime_start.setEnabled(False)
            self.dlg.week_days.setEnabled(False)
            self.dlg.weekends.setEnabled(False)
            self.dlg.no_distinction.setEnabled(False)
        else:
            self.dlg.dateTime_stop.setEnabled(True)
            self.dlg.dateTime_start.setEnabled(True)
            self.dlg.week_days.setEnabled(True)
            self.dlg.weekends.setEnabled(True)
            self.dlg.no_distinction.setEnabled(True)
    
    
    #To search the file name (path)of the area of interest when the user click on the search button
    def search_file(self):
        if self.dlg.search_button.isDown():
            pass
        else:
            fname, _ = QFileDialog.getOpenFileName(None, 'Select a file', 
                                            '', "Shapefiles (*.shp);;All Files (*)")
            self.dlg.line_polygon.clear()
            self.dlg.line_polygon.insert(fname)
        
        self.dlg.search_button.setDown(True)
    
    
    def def_coord(self, selectedProvinces):
        if selectedProvinces == "All provinces":
            #coordinates for Lombardia
            x_p=9.930278
            y_p=45.585556
        
        else:
            if selectedProvinces == "BG - Bergamo":
                #coordinates for Bergamo
                x_p=9.66895
                y_p=45.69798
            elif selectedProvinces == "BS - Brescia":
                #coordinates for Brescia
                x_p=10.211802
                y_p=45.541553
            elif selectedProvinces == "CO - Como":
                #coordinates for Como
                x_p=9.092748
                y_p=45.799281
            elif selectedProvinces == "CR - Cremona":
                #coordinates for Cremona
                x_p=9.983658
                y_p=45.201438
            elif selectedProvinces == "LC - Lecco":
                #coordinates for Lecco
                x_p=9.39005
                y_p=45.85317
            elif selectedProvinces == "LO - Lodi":
                #coordinates for Lodi
                x_p=9.50286
                y_p=45.31357
            elif selectedProvinces == "MN - Mantova":
                #coordinates for Mantova
                x_p=10.79784
                y_p=45.16031
            elif selectedProvinces == "MI - Milano":
                #coordinates for Milano
                x_p=9.18951
                y_p=45.46427
            elif selectedProvinces == "MB - Monza e della Brianza":
                #coordinates for Monza e della Brianza
                x_p=9.2730143
                y_p=45.5840057
            elif selectedProvinces == "PV - Pavia":
                #coordinates for Pavia
                x_p=9.15917
                y_p=45.19205
            elif selectedProvinces == "SO - Sondrio":
                #coordinates for Sondrio
                x_p=9.878767
                y_p=46.169858  
                
            elif selectedProvinces == "VA - Varese":
                #coordinates for Varese
                x_p=8.82193
                y_p=45.82908
        ret=(x_p,y_p)
        return ret
        
    #Request ARPA data to get the station location and information from the selected dataset 
    def request_ARPA_stations(self,client, dataset_num, datasetId, sensors, selected_aoi, geom, provinces):
        stations_json={}
        if dataset_num==1 or dataset_num==2:
                
            #For weather data
            if dataset_num == 1:
                query = """
                    select
                        *
                    where (storico='N') and (tipologia=\'{}\'""".format(sensors[0])
                
                for sensor in sensors[1:]:
                    query=query+" or tipologia=\'{}\'".format(sensor)
                    
                query = query+")"
                
                
                
            #For air quality data
            elif dataset_num == 2:
                query = """
                    select
                        *
                    where (storico='N') and (nometiposensore=\'{}\'""".format(sensors[0])
                for sensor in sensors[1:]:
                    query=query+" or nometiposensore=\'{}\'".format(sensor)
                
                query = query+")"
                
                
        
            if selected_aoi == "Insert area":
                polygon=geom.asWkt()
                tolerence=0.005
                while len(polygon)>10000 and tolerence <100:
                    polygon=geom.simplify(tolerence).asWkt()
                    tolerence=tolerence*2
                    
                query=query+" and within_polygon(location, \'{}\')".format(polygon)
                    
            elif selected_aoi == "Lombardia":
                if provinces != "All provinces" and provinces != "":
                    query=query+" and provincia = \'{}\'".format(provinces[0:2])
            
            print(len(query))
            
            try:
                stations_json = client.get(datasetId, query=query)
            
            except:
                QApplication.beep() 
                self.iface.messageBar().pushMessage("The area selected has too much points", Qgis.Warning)
                stations_json = {}
                    
        
        return stations_json

    
    #Get the areas of interest contained in the shapefile
    def get_areas_of_interest(self):
        #get the shapefile name entered by the user
        file_name = self.dlg.line_polygon.text()
        
        if file_name == '':
            QApplication.beep() 
            self.iface.messageBar().pushMessage("Area of interest not inserted", Qgis.Warning)
        
        layer_aoi = QgsVectorLayer(file_name, 'Area of interest', 'ogr')
        l_features=layer_aoi.getFeatures(QgsFeatureRequest())
        
        #stores all the geometries
        geoms=[]
        for feat in l_features:
            geoms.append(feat.geometry())
            if feat.geometry().wkbType()==QGis.WKBMultiPolygon:
                print("gooood")
            # qgis.core.QgsWkbTypes.displayString(int(layer.wkbType()))
        return geoms


    #Request the ARPA data for one particular sensor between start_date and end_date
    def req_ARPA_data_sensor(self,client,id_sensor, dataset_num,start_date,end_date):
        data_sensor = {}
        query = """
            select
                *
            where data between \'{}\' and \'{}\' and idsensore=\'{}\' 
            """.format(start_date,end_date, id_sensor)
        
        if dataset_num == 1 :
            data_sensor = client.get("647i-nhxk",query=query)
        elif dataset_num == 2:
            data_sensor = client.get("nicp-bhqi",query=query)
        elif dataset_num <=0:
            print("Initial value OK")
            
        else:
            print("No valid value for dataset number")
            
        return data_sensor
                 

    

    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = ARPAdataDialog()
        

        # Clear the contents from previous runs
        self.dlg.dataset_list.clear()
        self.dlg.area_list.clear()
        self.dlg.province_list.clear()
        self.dlg.sensor_type_list.clear()
        self.dlg.without_data.setChecked(False)
        self.dlg.all_sensors.setChecked(False)
        self.dlg.week_days.setChecked(True)
        self.dlg.weekends.setChecked(True)
        self.dlg.no_distinction.setChecked(True)
        self.dlg.line_polygon.clear()
        
        
        # Populate the comboBox of datasets with names of all the possible dataset
        self.dlg.dataset_list.addItems(["","Weather", "Air Quality"])
        
        #Modify the list of sensors, the starting date and the ending date propositions depending on the selected dataset
        self.dlg.dataset_list.currentIndexChanged.connect(self.on_dataset_changed, self.dlg.dataset_list.currentIndex())
        
        #Modify the starting date possibility and ending date possibilities to avoid end < start
        self.dlg.dateTime_stop.dateChanged.connect(lambda: self.dlg.dateTime_start.setMaximumDateTime(self.dlg.dateTime_stop.dateTime()))
        self.dlg.dateTime_start.dateChanged.connect(lambda: self.dlg.dateTime_stop.setMinimumDateTime(self.dlg.dateTime_start.dateTime()))
        
        #Select or Deselect all the sensors if all_sensors is checked/unchecked
        self.dlg.all_sensors.stateChanged.connect(lambda: self.on_check_changed(self.dlg.all_sensors.isChecked()))
        
        #Modify the checkboxes for week_days, weekends or no_distinction
        self.dlg.week_days.stateChanged.connect(lambda: self.on_check_day_changed(self.dlg.week_days.isChecked(), self.dlg.weekends.isChecked()))
        self.dlg.weekends.stateChanged.connect(lambda: self.on_check_day_changed(self.dlg.week_days.isChecked(), self.dlg.weekends.isChecked()))
        
        # Populate the comboBox of area with the possible options
        self.dlg.area_list.addItems(["Lombardia","Insert area"])
        
        # Populate the comboBox of provinces with the possible options
        self.dlg.province_list.clear()
        self.dlg.province_list.addItems(["All provinces","BG - Bergamo", "BS - Brescia", "CO - Como", "CR - Cremona", "LC - Lecco", 
                                           "LO - Lodi", "MN - Mantova", "MI - Milano", "MB - Monza e della Brianza", "PV - Pavia", 
                                           "SO - Sondrio", "VA - Varese"])
        
        #Modify the insert line for polygon depending on the choice of the user about the area (all lombardia or insert area)
        self.dlg.area_list.currentIndexChanged.connect(lambda: self.on_area_changed(self.dlg.area_list.currentText()))
        
        #Desable/Enable the time filters depending on the check/uncheck of the without data button
        self.dlg.without_data.stateChanged.connect(lambda: self.on_without_data_changed(self.dlg.without_data.isChecked()))
        
        #Search the file name (path)of the area of interest when the user click on the search button
        self.dlg.search_button.clicked.connect(lambda: self.search_file())
        
        
        # TO HAVE THE LAYERS OF THE CURRENT PROJECT
        # layers = QgsProject.instance().mapLayers().values()
        # layers_list=list(layers)
        
        # l_features=layers_list[2].getFeatures(QgsFeatureRequest())
        # print(layers_list[2].name())
        # for feat in l_features:
        #     print(feat)
        #     print(feat.fields())
        #     print(feat.geometry)
        
        
        #TO HAVE THE LAYER FROM AN INPUT
        # fn = "C:/Users/mathi/Desktop/Tests_layers/area_of_interest.shp"
        # layer_test = QgsVectorLayer(fn, 'name', 'ogr')
        # l_features=layer_test.getFeatures(QgsFeatureRequest())
        # for feat in l_features:
        #     print(feat.geometry().asWkt())
    
    
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        
        # See if OK was pressed
        if result:
            
            #get the user choices regarding the time
            selected_data_start = self.dlg.dateTime_start.dateTime()
            selected_date_start_str = selected_data_start.toString("yyyy-MM-ddTHH:mm:ss")
            
            selected_date_end = self.dlg.dateTime_stop.dateTime()
            selected_date_end_str = selected_date_end.toString("yyyy-MM-ddTHH:mm:ss")
            
            
            #get the user choices regarding the days of the week
            weekdays = self.dlg.week_days.isChecked()
            weekends = self.dlg.weekends.isChecked()
            no_distinction = self.dlg.no_distinction.isChecked()
            
            #get the user choice regarding the dataset 
            selectedDatasetIndex = self.dlg.dataset_list.currentIndex()
            
            #get the user choice regarding the area of interest
            selectedArea = self.dlg.area_list.currentText()
            
            #get the user choice regarding the provinces
            selectedProvinces = self.dlg.province_list.currentText()
            
            #get the user choice for the sensor types
            selectedSensors = self.dlg.sensor_type_list.selectedItems()
            
            
            if selectedDatasetIndex != 0:
                
                if len(selectedSensors)>0:
                    
                    without_data = self.dlg.without_data.isChecked() 
                    
                    #Define the dataset id according to the user choice
                    if selectedDatasetIndex == 1: 
                        datasetId="nf78-nj6b"
                    elif selectedDatasetIndex==2:
                        datasetId="ib47-atvt"
                    
                    #create the list of selected sensors
                    selectedSensors_list =[]
                    
                    #dictionnary that will contain, for each sensor, a list with the monitoring values (useful to make stat per sensor)
                    for i in selectedSensors:
                        selectedSensors_list.append(i.text())
            
                    #request data for stations
                    client= self.connect_ARPI_api()
                    
                    
                    if selectedArea == "Insert area":
                        geoms=self.get_areas_of_interest()
                    
                    elif selectedArea == "Lombardia":
                        geoms=["Lombardia"] #just to have one single loop in the for loop
                    
                    #index providing the number of the area if multiple polygons are entered
                    index=0
                    
                    #We loop on the geoms to have one request per area of interest
                    for geom_area in geoms:
                        index+=1
                        stations = self.request_ARPA_stations(client, selectedDatasetIndex, datasetId, selectedSensors_list, selectedArea, geom_area, selectedProvinces)
                    
                        if stations != {}:
                            
                            #dictionnary that will contain, for each sensor, a list with the monitoring values (useful to make stat per sensor)
                            sensor_dic = {}
                            for i in selectedSensors:
                                if no_distinction:
                                    sensor_dic[i.text()]=[]
                                else:
                                    sensor_dic[i.text()]={"Week_days":[], "Week_ends":[]}
                            
                            #Conversion to GEOJSON
                            stations_dic = {
                                "type": "FeatureCollection",
                                "features": [
                                {
                                    "type": "Feature",
                                    "geometry" : {
                                        "type": "Point",
                                        "coordinates": [d["lng"], d["lat"]],
                                        },
                                    "properties" : d,
                                  } for d in stations]
                                }
                            
                           
                            #Layers characteristics
                            
                            common_stats_fields = [('mean_value',QVariant.Double), ('count',QVariant.Double),  
                                      ('min_value', QVariant.Double), ('max_value', QVariant.Double),
                                      ('median_value', QVariant.Double), ('stdev', QVariant.Double)]
                            
                            all_stats_fields = []
                            
                            if selectedProvinces == "All provinces":
                                area_name='Lombardia'
                            elif selectedProvinces == "":
                                area_name='Area '+str(index)
                            else:
                                area_name = selectedProvinces[5:]
                            
                            
                            #For Weather data
                            if selectedDatasetIndex == 1 :
                                name = "Weather stations "+area_name
                                data_stat_name= "Weather data - Statistics per sensor "+area_name
                                stat_all_name= "Weather data - Statistics for the whole area "+area_name
                                fields = [("idsensore",QVariant.Int),("tipologia",QVariant.String),
                                      ("unit_dimisura", QVariant.String), ("idstazione", QVariant.Int),
                                      ("nomestazione",QVariant.String),("quota", QVariant.Double),
                                      ("provincia",QVariant.String), ("datastart",QVariant.String),
                                      ("datastop",QVariant.String),("storico", QVariant.String),
                                      ("cgb_nord",QVariant.Int),("cgb_est",QVariant.Int), 
                                      ("lng", QVariant.Double),("lat", QVariant.Double)]
                                data_stats_fields = [("idsensore",QVariant.Int),("tipologia",QVariant.String),
                                      ("idstazione", QVariant.Int),("nomestazione",QVariant.String),
                                      ("provincia",QVariant.String),("lng", QVariant.Double),("lat", QVariant.Double),
                                      ("unit_dimisura", QVariant.String)]
                                for sensor in selectedSensors_list:
                                    all_stats_fields.append((sensor+" unit_dimisura", QVariant.String))
                                    all_stats_fields.append((sensor+' mean_value',QVariant.Double))
                                    all_stats_fields.append((sensor+' count',QVariant.Double))
                                    all_stats_fields.append((sensor+' min_value', QVariant.Double))
                                    all_stats_fields.append((sensor+' max_value', QVariant.Double))
                                    all_stats_fields.append((sensor+' median_value', QVariant.Double))
                                    all_stats_fields.append((sensor+' stdev', QVariant.Double))
                                name_type="tipologia"
                                unit_measure="unit_dimisura"
                                
                            #For Air Quality data
                            elif selectedDatasetIndex == 2 :
                                name = "Air pollution stations "+area_name
                                data_stat_name= "Air pollution - Statistics per sensor "+area_name
                                stat_all_name="Air pollution - Statistics for the whole area "+area_name
                                fields = [("idsensore",QVariant.Int),("nometiposensore",QVariant.String),
                                      ("unitamisura", QVariant.String), ("idstazione", QVariant.Int),
                                      ("nomestazione",QVariant.String),("quota", QVariant.Double),
                                      ("provincia",QVariant.String), ("comune",QVariant.String), 
                                      ("datastart",QVariant.String),("datastop",QVariant.String),
                                      ("storico", QVariant.String),("utm_nord",QVariant.Int),
                                      ("utm_est",QVariant.Int), ("lng", QVariant.Double),
                                      ("lat", QVariant.Double)]
                                data_stats_fields = [('idsensore',QVariant.Int), ("nometiposensore",QVariant.String),
                                      ("idstazione", QVariant.Int),("nomestazione",QVariant.String),
                                      ("provincia",QVariant.String), ("comune",QVariant.String),
                                      ("lng", QVariant.Double), ("lat", QVariant.Double),("unitamisura", QVariant.String)]
                                
                                for sensor in selectedSensors_list:
                                    all_stats_fields.append((sensor+" unitamisura", QVariant.String))
                                    all_stats_fields.append((sensor+' mean_value',QVariant.Double))
                                    all_stats_fields.append((sensor+' count',QVariant.Double))
                                    all_stats_fields.append((sensor+' min_value', QVariant.Double))
                                    all_stats_fields.append((sensor+' max_value', QVariant.Double))
                                    all_stats_fields.append((sensor+' median_value', QVariant.Double))
                                    all_stats_fields.append((sensor+' stdev', QVariant.Double))
                                name_type="nometiposensore"
                                unit_measure="unitamisura"
                            
                            data_stats_fields.extend(common_stats_fields)
                        
                            #Creation of the layers 
                                
                            #create the vector layer for stations
                            vl = QgsVectorLayer("Point?crs=EPSG:4326", name, "memory")
                            vl.startEditing()
                            pr = vl.dataProvider()
                            
                            #Add the fields
                            qgs_f=QgsFields()
                            for field in fields:
                                qgs_f.append(QgsField(field[0],field[1]))
                            pr.addAttributes(qgs_f)
                            vl.updateFields()
                            vl.commitChanges()
                            
                            if not without_data:
                                
                                if no_distinction: 
                                    # create the layer containing the statatistics of monitoring data for each sensor
                                    vl_stat_data = QgsVectorLayer("Point?crs=EPSG:4326", data_stat_name, 'memory')
                                    vl_stat_data.startEditing()
                                    pr_stat_data = vl_stat_data.dataProvider()
                                    
                                    #Add the fields
                                    qgs_f_data=QgsFields()
                                    for field in data_stats_fields:
                                        qgs_f_data.append(QgsField(field[0],field[1]))
                                    pr_stat_data.addAttributes(qgs_f_data)
                                    vl_stat_data.updateFields()
                                    vl_stat_data.commitChanges()
                                    
                                                        
                                    #create the layer containing the statistics of monitoring data for the all area of interest
                                    vl_stat_all = QgsVectorLayer("Point?crs=EPSG:4326", stat_all_name, 'memory')
                                    vl_stat_all.startEditing()
                                    pr_stat_all = vl_stat_all.dataProvider()
                                
                                    #create the layer containing the statistics of monitoring data for the all area of interest
                                    vl_stat_all = QgsVectorLayer("Point?crs=EPSG:4326", stat_all_name, 'memory')
                                    vl_stat_all.startEditing()
                                    pr_stat_all = vl_stat_all.dataProvider()
                                
                                    #Add the fields
                                    qgs_f_stats_all=QgsFields()
                                    for field in all_stats_fields:
                                        qgs_f_stats_all.append(QgsField(field[0],field[1]))
                                    pr_stat_all.addAttributes(qgs_f_stats_all)
                                    vl_stat_all.updateFields()
                                    vl_stat_all.commitChanges()
                        
                                else:
                                    #for week_days
                                    if weekdays:
                                        #create a layer for week days
                                        vl_stat_data_weekdays = QgsVectorLayer("Point?crs=EPSG:4326", data_stat_name+' - week days', 'memory')
                                        vl_stat_data_weekdays.startEditing()
                                        pr_stat_data_weekdays = vl_stat_data_weekdays.dataProvider()
                                        
                                        #Add the fields
                                        qgs_f_data_weekdays=QgsFields()
                                        for field in data_stats_fields:
                                            qgs_f_data_weekdays.append(QgsField(field[0],field[1]))
                                        pr_stat_data_weekdays.addAttributes(qgs_f_data_weekdays)
                                        vl_stat_data_weekdays.updateFields()
                                        vl_stat_data_weekdays.commitChanges()
                                        
                                                            
                                        #create the layer containing the statistics of monitoring data for the all area of interest for week days
                                        vl_stat_all_weekdays = QgsVectorLayer("Point?crs=EPSG:4326", stat_all_name+' - week days', 'memory')
                                        vl_stat_all_weekdays.startEditing()
                                        pr_stat_all_weekdays = vl_stat_all_weekdays.dataProvider()
                                    
                                        #Add the fields
                                        qgs_f_stats_all_weekdays=QgsFields()
                                        for field in all_stats_fields:
                                            qgs_f_stats_all_weekdays.append(QgsField(field[0],field[1]))
                                        pr_stat_all_weekdays.addAttributes(qgs_f_stats_all_weekdays)
                                        vl_stat_all_weekdays.updateFields()
                                        vl_stat_all_weekdays.commitChanges()
                                    
                                    #for weekends
                                    if weekends:
                                        #create a layer for weekends
                                        vl_stat_data_weekends = QgsVectorLayer("Point?crs=EPSG:4326", data_stat_name+' - weekends', 'memory')
                                        vl_stat_data_weekends.startEditing()
                                        pr_stat_data_weekends = vl_stat_data_weekends.dataProvider()
                                        
                                        #Add the fields
                                        qgs_f_data_weekends=QgsFields()
                                        for field in data_stats_fields:
                                            qgs_f_data_weekends.append(QgsField(field[0],field[1]))
                                        pr_stat_data_weekends.addAttributes(qgs_f_data_weekends)
                                        vl_stat_data_weekends.updateFields()
                                        vl_stat_data_weekends.commitChanges()
                                        
                                                            
                                        #create the layer containing the statistics of monitoring data for the all area of interest for week days
                                        vl_stat_all_weekends = QgsVectorLayer("Point?crs=EPSG:4326", stat_all_name+' - weekends', 'memory')
                                        vl_stat_all_weekends.startEditing()
                                        pr_stat_all_weekends = vl_stat_all_weekends.dataProvider()
                                    
                                        #Add the fields
                                        qgs_f_stats_all_weekends=QgsFields()
                                        for field in all_stats_fields:
                                            qgs_f_stats_all_weekends.append(QgsField(field[0],field[1]))
                                        pr_stat_all_weekends.addAttributes(qgs_f_stats_all_weekends)
                                        vl_stat_all_weekends.updateFields()
                                        vl_stat_all_weekends.commitChanges()
                                    
                            #Variable to check if in the end there is no weekend day or week days in the range of time selected
                            no_weekdays=True
                            no_weekends=True
                            
                            #Add all the features for the stations
                            for feature in stations_dic['features']:
                
                                f = QgsFeature()
                                
                                x=float(feature['geometry']['coordinates'][0])
                                y=float(feature['geometry']['coordinates'][1])
                                geom = QgsGeometry.fromPointXY(QgsPointXY(QgsPoint(x,y)))
                                f.setGeometry(geom)
                                f.setFields(qgs_f)
                                
                                attributes=list(feature['properties'].items())
                                for att in attributes:
                                    if att[0]!= "location" and att[0]!=':@computed_region_6hky_swhk' and att[0]!=':@computed_region_ttgh_9sm5':
                                        f[att[0]] = att[1]
                               
                                pr.addFeature(f)
                                vl.updateExtents()
                                
            
                                #For each sensor, we request the data and compute the statistics 
                                if not without_data:
                                    id_sensor = feature['properties']['idsensore']
                                    data_sensor = self.req_ARPA_data_sensor(client, id_sensor, selectedDatasetIndex, selected_date_start_str, selected_date_end_str)
                                    if len(data_sensor)>0 :
                                        
                                        #if there is no distinction between weekdays and weekends
                                        if no_distinction:
                                            
                                            #Create one new feature per sensor
                                            d = QgsFeature()
                                            d.setFields(qgs_f_data)
                                            
                                            #Add the attributes of the sensor as previously
                                            for att in attributes:
                                                try:
                                                    d[att[0]] = att[1]
                                                except:
                                                    # print('no_attribute '+att[0])
                                                    pass
                                                                    
                                            # Compute the statistics per sensor with all the data acquired
                                            list_val=[]
                                                    
                                            for data in data_sensor:
                                                if float(data['valore']) != -9999:
                                                    list_val.append(float(data['valore']))
                                                    #Add the value to the sensor_dic to compute the stat at the end
                                                    sensor_dic[feature['properties'][name_type]].append(float(data['valore']))
                                          
                                            if len(list_val)>0:
                                                d['max_value'] = max(list_val)
                                                d['min_value'] = min(list_val)
                                                d['mean_value'] = statistics.mean(list_val)
                                                d['count'] = len(list_val)
                                                d['median_value'] = statistics.median(list_val)
                                                
                                                if len(list_val)>1:
                                                    d['stdev']= statistics.stdev(list_val)
                                                    
                                                #Add the geometry to the data 
                                                x=float(feature['geometry']['coordinates'][0])
                                                y=float(feature['geometry']['coordinates'][1])
                                                geom_data = QgsGeometry.fromPointXY(QgsPointXY(QgsPoint(x,y)))
                                                d.setGeometry(geom_data)
                                                
                                                pr_stat_data.addFeature(d)
                                                vl_stat_data.updateExtents()
                                            
                                            else:
                                                print("LIST VAL IS EMPTY")
                                                pass
                                            
                                        
                                        #If there is a distinction between weekdays and weekends
                                        else:
                                            
                                            list_val_weekdays=[]
                                            list_val_weekends=[]
                                            for data in data_sensor:
                                                if float(data['valore']) != -9999:
                                                    data_date=datetime.datetime.strptime(data['data'][0:10], "%Y-%m-%d")
                                                    day=data_date.weekday()
                                                    if weekdays and day >=0 and day <=4:
                                                        list_val_weekdays.append(float(data['valore']))
                                                        #Add the value to the sensor_dic to compute the stat at the end
                                                        sensor_dic[feature['properties'][name_type]]['Week_days'].append(float(data['valore']))
                                                    if weekends and day >=5 and day <=6:
                                                        list_val_weekends.append(float(data['valore']))
                                                        #Add the value to the sensor_dic to compute the stat at the end
                                                        sensor_dic[feature['properties'][name_type]]['Week_ends'].append(float(data['valore']))
                                                            
                                            if weekdays:
                                                
                                                if len(list_val_weekdays)>0:
                                                    no_weekdays=False
                                                    #Create one new feature per sensor
                                                    d_weekdays = QgsFeature()
                                                    d_weekdays.setFields(qgs_f_data_weekdays)
                                                    
                                                    #Add the attributes of the sensor as previously
                                                    for att in attributes:
                                                        try:
                                                            d_weekdays[att[0]] = att[1]
                                                        except:
                                                            # print('no_attribute '+att[0])
                                                            pass
                                                
                                                    d_weekdays['max_value'] = max(list_val_weekdays)
                                                    d_weekdays['min_value'] = min(list_val_weekdays)
                                                    d_weekdays['mean_value'] = statistics.mean(list_val_weekdays)
                                                    d_weekdays['count'] = len(list_val_weekdays)
                                                    d_weekdays['median_value'] = statistics.median(list_val_weekdays)
                                                    
                                                    if len(list_val_weekdays)>1:
                                                        d_weekdays['stdev']= statistics.stdev(list_val_weekdays)
                                                    
                                                    #Add the geometry to the data 
                                                    x=float(feature['geometry']['coordinates'][0])
                                                    y=float(feature['geometry']['coordinates'][1])
                                                    geom_data = QgsGeometry.fromPointXY(QgsPointXY(QgsPoint(x,y)))
                                                    d_weekdays.setGeometry(geom_data)
                                                    
                                                    pr_stat_data_weekdays.addFeature(d_weekdays)
                                                    vl_stat_data_weekdays.updateExtents()
                                                
                                                else:
                                                    pass
                                                                                
                                            if weekends:
                                                
                                                if len(list_val_weekends)>0:
                                                    no_weekends=False
                                                    #Create one new feature per sensor
                                                    d_weekends = QgsFeature()
                                                    d_weekends.setFields(qgs_f_data_weekends)
                                                    
                                                    #Add the attributes of the sensor as previously
                                                    for att in attributes:
                                                        try:
                                                            d_weekends[att[0]] = att[1]
                                                        except:
                                                            # print('no_attribute '+att[0])
                                                            pass
                                                    
                                                    d_weekends['max_value'] = max(list_val_weekends)
                                                    d_weekends['min_value'] = min(list_val_weekends)
                                                    d_weekends['mean_value'] = statistics.mean(list_val_weekends)
                                                    d_weekends['count'] = len(list_val_weekends)
                                                    d_weekends['median_value'] = statistics.median(list_val_weekends)
                                                    
                                                    if len(list_val_weekends)>1:
                                                        d_weekends['stdev']= statistics.stdev(list_val_weekends)
                                                    
                                                    #Add the geometry to the data 
                                                    x=float(feature['geometry']['coordinates'][0])
                                                    y=float(feature['geometry']['coordinates'][1])
                                                    geom_data = QgsGeometry.fromPointXY(QgsPointXY(QgsPoint(x,y)))
                                                    d_weekends.setGeometry(geom_data)
                                                    
                                                    pr_stat_data_weekends.addFeature(d_weekends)
                                                    vl_stat_data_weekends.updateExtents()
                                                
                                                else:
                                                    pass
                                                 
                                        
                            
                           
                            
                            #Add the layer containing only stations location
                            q=QgsProject.instance()
                            q.addMapLayer(vl)
                            
                            
                            if not without_data:
                                
                                if no_distinction:
                                    
                                    #Add the layer with the statistics for each sensor 
                                    q.addMapLayer(vl_stat_data)
                                    
                                    #create the only point of the layer
                                    p = QgsFeature()
                                    p.setFields(qgs_f_stats_all)
                                    
                                    empty_sensors=[]
                                    
                                    for sensor in selectedSensors_list:
                                        
                                        #Compute the general statistics for the whole area
                                        list_values=sensor_dic[sensor]
                                        
                                        if len(list_values)>0:
                                            p[sensor+' max_value'] = max(list_values)
                                            p[sensor+' min_value'] = min(list_values)
                                            p[sensor+' mean_value'] = statistics.mean(list_values)
                                            p[sensor+' count'] = len(list_values)
                                            p[sensor+' median_value'] = statistics.median(list_values)
                                            if len(list_values)>1:
                                                    p[sensor+' stdev']= statistics.stdev(list_values)
                                            p[sensor+' '+unit_measure] = stations_dic['features'][0]['properties'][unit_measure]
                                        
                                        else:
                                            self.iface.messageBar().pushMessage("No data for the sensors "+sensor, Qgis.Warning)
                                            empty_sensors.append(sensor)
                                    
                                    
                                            
                                    #Add the geometry to the data 
                                    
                                    #If it is an inserted area, we take the centroid of it
                                    if selectedArea == "Insert area":
                                        #Coordinates of the centroid
                                        point=geom_area.centroid().asPoint()
                                        x_p=point.x()
                                        y_p=point.y()
    
                                    #Otherwise it is Lombardia and it depends on the selected Provinces
                                    else:
                                        (x_p,y_p) = self.def_coord(selectedProvinces)
                                        
                                    geom_data = QgsGeometry.fromPointXY(QgsPointXY(QgsPoint(x_p,y_p)))
                                    p.setGeometry(geom_data)
                                    
                                    #Add the point to the layer
                                    pr_stat_all.addFeature(p)
                                    vl_stat_all.updateExtents()
                                    
                                    vl_stat_all.startEditing()
                                    for s in empty_sensors:
                                        list_fields=pr_stat_all.fields()
                                        pr_stat_all.deleteAttributes([list_fields.indexFromName(s+' max_value'), 
                                                                          list_fields.indexFromName(s+' min_value'),
                                                                          list_fields.indexFromName(s+' count'),
                                                                          list_fields.indexFromName(s+' median_value'),
                                                                          list_fields.indexFromName(s+' stdev'),
                                                                          list_fields.indexFromName(s+' '+unit_measure),
                                                                          list_fields.indexFromName(s+' mean_value')])
                                    vl_stat_all.commitChanges()
                                    
                                    #Add the layer with the general statistics for the whole area
                                    q.addMapLayer(vl_stat_all)
                                
                               
                                else:
                                    if weekdays:
                                        
                                        empty_sensors_weekdays=[]
                                        
                                        #Check if they is weekdays data
                                        if not no_weekdays:
                                            #Add the layer with the statistics for each sensor in week days
                                            q.addMapLayer(vl_stat_data_weekdays)
                                            
                                            #create the only point of the layer for week days
                                            p_weekdays = QgsFeature()
                                            p_weekdays.setFields(qgs_f_stats_all_weekdays)
                                            
                                            for sensor in selectedSensors_list:
                                                
                                                #Compute the general statistics for the whole area
                                                list_values=sensor_dic[sensor]['Week_days']
                                                
                                                if len(list_values)>0:
                                                    p_weekdays[sensor+' max_value'] = max(list_values)
                                                    p_weekdays[sensor+' min_value'] = min(list_values)
                                                    p_weekdays[sensor+' mean_value'] = statistics.mean(list_values)
                                                    p_weekdays[sensor+' count'] = len(list_values)
                                                    p_weekdays[sensor+' median_value'] = statistics.median(list_values)
                                                    if len(list_values)>1:
                                                            p_weekdays[sensor+' stdev']= statistics.stdev(list_values)
                                                    p_weekdays[sensor+' '+unit_measure] = stations_dic['features'][0]['properties'][unit_measure]
                                                
                                                else:
                                                    self.iface.messageBar().pushMessage("No data on the selected weekdays for the sensors "+sensor, Qgis.Warning)
                                                    empty_sensors_weekdays.append(sensor)
                                                    
                                            
                                            #Add the geometry to the data 
                                            #If it is an inserted area, we take the centroid of it
                                            if selectedArea == "Insert area":
                                                #Coordinates of the centroid
                                                point=geom_area.centroid().asPoint()
                                                x_p=point.x()
                                                y_p=point.y()
                                            
                                            #Otherwise it is Lombardia and it depends on the selected Provinces
                                            else:
                                                (x_p,y_p) = self.def_coord(selectedProvinces)
                                            
                                            geom_data = QgsGeometry.fromPointXY(QgsPointXY(QgsPoint(x_p,y_p)))
                                            p_weekdays.setGeometry(geom_data)
                                            
                                            
                                            #Add the point to the layer
                                            pr_stat_all_weekdays.addFeature(p_weekdays)
                                            vl_stat_all_weekdays.updateExtents()
                                            
                                            
                                            vl_stat_all_weekdays.startEditing()
                                            for s in empty_sensors_weekdays:
                                                list_fields=pr_stat_all_weekdays.fields()
                                                pr_stat_all_weekdays.deleteAttributes([list_fields.indexFromName(s+' max_value'), 
                                                                                  list_fields.indexFromName(s+' min_value'),
                                                                                  list_fields.indexFromName(s+' count'),
                                                                                  list_fields.indexFromName(s+' median_value'),
                                                                                  list_fields.indexFromName(s+' stdev'),
                                                                                  list_fields.indexFromName(s+' '+unit_measure),
                                                                                  list_fields.indexFromName(s+' mean_value')])
                                            vl_stat_all_weekdays.commitChanges()
                                            
                                            #Add the layer with the general statistics for the whole area
                                            q.addMapLayer(vl_stat_all_weekdays)
                                            
                                            
                                        
                                        else :
                                            self.iface.messageBar().pushMessage("No data for these weekdays", Qgis.Warning)
                                    
                                    
                                    if weekends :
                                        
                                        empty_sensors_weekends=[]
                                        
                                        #Check if they is weekdays data
                                        if not no_weekends:
                                            
                                            #Add the layer with the statistics for each sensor in weekends
                                            q.addMapLayer(vl_stat_data_weekends)
                                            
                                            #create the only point of the layer for week days
                                            p_weekends = QgsFeature()
                                            p_weekends.setFields(qgs_f_stats_all_weekends)
                                            
                                            for sensor in selectedSensors_list:
                                                
                                                #Compute the general statistics for the whole area
                                                list_values=sensor_dic[sensor]['Week_ends']
                                                
                                                if len(list_values)>0:
                                                    p_weekends[sensor+' max_value'] = max(list_values)
                                                    p_weekends[sensor+' min_value'] = min(list_values)
                                                    p_weekends[sensor+' mean_value'] = statistics.mean(list_values)
                                                    p_weekends[sensor+' count'] = len(list_values)
                                                    p_weekends[sensor+' median_value'] = statistics.median(list_values)
                                                    if len(list_values)>1:
                                                            p_weekends[sensor+' stdev']= statistics.stdev(list_values)
                                                    p_weekends[sensor+' '+unit_measure] = stations_dic['features'][0]['properties'][unit_measure]
                                                
                                                else:
                                                    self.iface.messageBar().pushMessage("No data on the selected weekends for the sensors "+sensor, Qgis.Warning)
                                                    empty_sensors_weekends.append(sensor)
                                                    
                                            #Add the geometry to the data 
                                            #If it is an inserted area, we take the centroid of it
                                            if selectedArea == "Insert area":
                                                #Coordinates of the centroid
                                                point=geom_area.centroid().asPoint()
                                                x_p=point.x()
                                                y_p=point.y()
                                            
                                           
                                            #Otherwise it is Lombardia and it depends on the selected Provinces
                                            else:
                                                (x_p,y_p) = self.def_coord(selectedProvinces)
                                                    
                                            geom_data = QgsGeometry.fromPointXY(QgsPointXY(QgsPoint(x_p,y_p)))
                                            p_weekends.setGeometry(geom_data)
                                            
                                            #Add the point to the layer
                                            pr_stat_all_weekends.addFeature(p_weekends)
                                            vl_stat_all_weekends.updateExtents()
                                            
                                            vl_stat_all_weekends.startEditing()
                                            for s in empty_sensors_weekends:
                                                list_fields=pr_stat_all_weekends.fields()
                                                pr_stat_all_weekends.deleteAttributes([list_fields.indexFromName(s+' max_value'), 
                                                                                  list_fields.indexFromName(s+' min_value'),
                                                                                  list_fields.indexFromName(s+' count'),
                                                                                  list_fields.indexFromName(s+' median_value'),
                                                                                  list_fields.indexFromName(s+' stdev'),
                                                                                  list_fields.indexFromName(s+' '+unit_measure),
                                                                                  list_fields.indexFromName(s+' mean_value')])
                                            vl_stat_all_weekends.commitChanges()
                                            
                                            #Add the layer with the general statistics for the whole area
                                            q.addMapLayer(vl_stat_all_weekends)
                                            
                                        else:
                                            self.iface.messageBar().pushMessage("No data for these weekends", Qgis.Warning)
                        
                        else:
                            print("Nothing inside the stations dic")
                
                else :
                      QApplication.beep() 
                      self.iface.messageBar().pushMessage("No sensor selected", Qgis.Warning)
                        
            else:
                QApplication.beep() 
                self.iface.messageBar().pushMessage("No dataset selected", Qgis.Warning)


