# -*- coding: utf-8 -*-
"""
/***************************************************************************
 POLO
                                 A QGIS plugin
 Elabora automaticamente relátorios e mapas de focos de calor a partir do bando de dados FIRMS/NASA
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2021-01-29
        git sha              : $Format:%H$
        copyright            : (C) 2021 by Newton Coelho Monteiro
        email                : newtongel@gmail.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
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.core import QgsApplication
from qgis.core import QgsProject, Qgis
from qgis.core import QgsLayoutExporter
from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsCoordinateReferenceSystem
from qgis.core import QgsExpression
from datetime import datetime
import os
import processing


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


class POLO:
    """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',
            'POLO_{}.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'&POLO')

        # 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('POLO', 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/POLO/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Acessar os focos de calor'),
            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'&POLO'),
                action)
            self.iface.removeToolBarIcon(action)


    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 = POLODialog()

        # show the dialog
        self.dlg.show()

        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            # pass
            #Caminho a ser exportado

            #RESETE FOLDER PROCESS
            import shutil

            shutil.rmtree(
                os.path.expanduser('~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/'))
            os.mkdir(os.path.expanduser('~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/'))

            from shutil import copyfile
            copyfile(os.path.expanduser('~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/recursos/POLO.qgz'),
                     os.path.expanduser('~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/POLO.qgz'))

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Acessando informações de hidrografia",
                level=Qgis.Info, duration=45)

            
            # Hidrografia HIDROGRAPH

            # Donwload_KML_linhas DOWNLOAD KML_LINES
            processing.runAndLoadResults("native:filedownloader", {
                'URL': 'https://drive.google.com/uc?id=1qCULQd8MKynZChMlCZYiY1iXzJkhDbQD&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Hidrografia_.kml')})

            # Donwload_KML_poly DOWNLOAD KML_POLY
            processing.runAndLoadResults("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1RXbqteoxbYZ6L9F17R7aI8svpVYEQ4fe&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/HidrografiaPoly_.kml')})

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Adicionando informações de hidrografia",
                level=Qgis.Info, duration=15)

            # Hidrografia_linhas HIDROGRAPH LINES
            # Verificação de geometria GEOMETRY CHECK
            processing.runAndLoadResults("qgis:checkvalidity",
                                         {'INPUT_LAYER': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Hidrografia_.kml'),
                                             'METHOD': 2, 'IGNORE_RING_SELF_INTERSECTION': False,
                                             'VALID_OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Hidrografia.gpkg')})
            # Downlaod_Estilo DOWNLOAD STYLE
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1BNunj56yiljlb8petZ3Rv1SINMl9-XuR&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Hidrografia_.qml')})

            # Aplicar_Estilo APPLY STYLE
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Hidrografia.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Hidrografia_.qml')})

            # Hidrografia_Poly HIDROGRAPH POLIGON

            # Downlaod_Estilo DOWNLOAD STYLE
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1_-Tde-pw-RYZkrO9xMf7sXuhlgDA2iAK&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/HidrografiaPoly_.qml')})

            # Verificação de geometria GEOMETRY CHECK
            processing.runAndLoadResults("qgis:checkvalidity",
                                         {'INPUT_LAYER': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/HidrografiaPoly_.kml'),
                                             'METHOD': 2, 'IGNORE_RING_SELF_INTERSECTION': False,
                                             'VALID_OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/HidrografiaPoly.gpkg')})

            # Aplicar_Estilo APPLY STYLE
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/HidrografiaPoly.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/HidrografiaPoly_.qml')})


            # Sedes municipais Amazon Cities

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Acessando informações das sedes municipais",
                level=Qgis.Info, duration=30)

            # Donwload_KML_linhas DOWNLOAD KML_CITIES
            processing.runAndLoadResults("native:filedownloader", {
                'URL': 'https://drive.google.com/uc?id=1d6ah8AUZ_19Ze8BevZPxqD6vgOsPnL_w&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Sedes_Municipais_AM_.kml')})

            # Downlaod_Estilo DOWNLOAD STYLE CITIES
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/uc?id=1ORCC2uAfQMV_dstf1WE3KyyK61CmCRuX&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Sedes_Municipais_AM_.qml')})

            # Verificação de geometria GEOMETRY CITIES CHECK
            processing.runAndLoadResults("qgis:checkvalidity",
                                         {'INPUT_LAYER': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Sedes_Municipais_AM_.kml'),
                                             'METHOD': 2, 'IGNORE_RING_SELF_INTERSECTION': False,
                                             'VALID_OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Sedes_Municipais_AM.gpkg')})

            # Aplicar_Estilo APPLY CITIES STYLE
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Sedes_Municipais_AM.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Sedes_Municipais_AM_.qml')})


            # Vias de acesso ACCESS WAYS

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Acessando informações de vias, ramais e vicinais",
                level=Qgis.Info, duration=30)

            # Donwload KML das rodovias DOWNLOAD ACCESS WAYS KML
            processing.runAndLoadResults("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1qmWXKmJUbAdzcKmNqddnJgkH6pFDAmpR&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Rodovias_.kml')})

            # Verificação de geometria GEOMETRY CHECK
            processing.runAndLoadResults("qgis:checkvalidity",
                                         {'INPUT_LAYER': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Rodovias_.kml'),
                                             'METHOD': 2, 'IGNORE_RING_SELF_INTERSECTION': False,
                                             'VALID_OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Vias de acesso.gpkg')})

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Adicionando informações de vias, estradas e ramais",
                level=Qgis.Info, duration=15)

            # Downlaod_Estilo DOWNLOAD STYLE
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1FBcVyOeszLd_8wk8EE0c5XzgqWxZVtEt&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Rodovias_.qml')})

            # Aplicar_Estilo APPLY STYLE
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Vias de acesso.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Rodovias_.qml')})

            # Municipio COUNTY

            # Donwload KML dos municipios DOWNLOAD COUNTY KML
            processing.runAndLoadResults("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1xVQBR5IuD9lTiSApTdXtwTuCdpGTeLLS&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Municipios_.kml')})

            # Verificação de geometria GEOMETRY CHECK
            processing.runAndLoadResults("qgis:checkvalidity",
                                         {'INPUT_LAYER': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Municipios_.kml'),
                                             'METHOD': 2, 'IGNORE_RING_SELF_INTERSECTION': False,
                                             'VALID_OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Limites municipais.gpkg')})

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Adicionando informações dos municípios e regiões",
                level=Qgis.Info, duration=15)

            # Downlaod_Estilo DOWNLOAD STYLE
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1kgF5AKGrof150-YmMeVTGgwhMGhgEDY1&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Municipios_.qml')})

            # Aplicar_Estilo APPLY STILE
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Limites municipais.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Municipios_.qml')})

            # Focos de calor HEAT POINTS

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Acessando informações de focos de calor",
                level=Qgis.Info, duration=15)

            # Donwload_CSV
            # LINK TESTE>> https://drive.google.com/u/0/uc?id=1tmNyvujgm-PRlZb_Cb14P6iiQ812wuHp&export=download
            # LINK FIRMS NASA https://firms.modaps.eosdis.nasa.gov/data/active_fire/c6/csv/MODIS_C6_South_America_7d.csv

            processing.run("native:filedownloader", {
                'URL': 'https://firms.modaps.eosdis.nasa.gov/data/active_fire/modis-c6.1/csv/MODIS_C6_1_South_America_7d.csv',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/DADOS.csv')})

            # Donwload_qml Focos de calor DOWNLOAD STYLE HEAT POINTS
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1K5nAihJBfjV7HcQ87soqqDNFg2SfBAtW&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/focosdecalor.qml')})

            # Donwload_qml Kernel DOWNLOAD STYLE FOR KERNEL HEAT POINTS
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=191MdbDgGvLbvlHfjlfE4TBoj9rXMuRv8&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Kernel.qml')})

            # CSV para gpkg CSV TO GPKG
            processing.run("native:createpointslayerfromtable", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/DADOS.csv'),
                'XFIELD': 'longitude', 'YFIELD': 'latitude', 'ZFIELD': '', 'MFIELD': '',
                'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'),
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Dados.gpkg')})

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Gerando análieses",
                level=Qgis.Info, duration=15)


            # Intersect focos INTERSECT HEAT POINTS
            processing.run("native:intersection",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Dados.gpkg'),
                               'OVERLAY': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Limites municipais.gpkg'),
                               'INPUT_FIELDS': [], 'OVERLAY_FIELDS': [], 'OVERLAY_FIELDS_PREFIX': '',
                               'OUTPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos_AM.gpkg')})

            # editar colunas para kernel ADJUST FIELD FOR KERNEL
            processing.runAndLoadResults("native:refactorfields",
                                         {'INPUT': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos_AM.gpkg'),
                                             'FIELDS_MAPPING': [
                                                 {'expression': '\"latitude\"', 'length': 0, 'name': 'latitude',
                                                  'precision': 0, 'type': 10},
                                                 {'expression': '\"longitude\"', 'length': 0, 'name': 'longitude',
                                                  'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"acq_date\"', 'length': 0, 'name': 'acq_date',
                                                  'precision': 0, 'type': 10},
                                                 {'expression': '\"satellite\"', 'length': 0, 'name': 'satellite',
                                                  'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"version\"', 'length': 0, 'name': 'version',
                                                  'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"NOME\"', 'length': 0, 'name': 'NOME', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"ESTADO\"', 'length': 0, 'name': 'ESTADO', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"Região\"', 'length': 0, 'name': 'Região', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"acq_date\"', 'length': 0, 'name': 'DATA', 'precision': 0,
                                                  'type': 14}],
                                             'OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Intensidade focos de calor.gpkg')})

            # Aplicar_Estilo para Kernel APPLY STYLE FOR KERNEL
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Intensidade focos de calor.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Kernel.qml')})

            # Editar colunas para focos de calor ADJUST FIELD FOR HEAT POINTS
            processing.runAndLoadResults("native:refactorfields",
                                         {'INPUT': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos_AM.gpkg'),
                                             'FIELDS_MAPPING': [
                                                 {'expression': '\"latitude\"', 'length': 0, 'name': 'latitude',
                                                  'precision': 0, 'type': 10},
                                                 {'expression': '\"longitude\"', 'length': 0, 'name': 'longitude',
                                                  'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"acq_date\"', 'length': 0, 'name': 'acq_date',
                                                  'precision': 0, 'type': 10},
                                                 {'expression': '\"satellite\"', 'length': 0, 'name': 'satellite',
                                                  'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"version\"', 'length': 0, 'name': 'version',
                                                  'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"NOME\"', 'length': 0, 'name': 'NOME', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"ESTADO\"', 'length': 0, 'name': 'ESTADO', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"Região\"', 'length': 0, 'name': 'Região', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"acq_date\"', 'length': 0, 'name': 'DATA', 'precision': 0,
                                                  'type': 14},
                                                 {'expression': '"acq_date"+\'T\'||left("acq_time",2)||\':\'||right("acq_time",2)+\':00Z\'','length': 0,'name': 'DATATIME','precision': 0,'sub_type': 0,'type': 16,'type_name': 'datetime'}],
                                             'OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos de calor.gpkg')})

            # Focos de Calor por cidade HEAT POINTS FOR CITYS
            processing.runAndLoadResults("qgis:statisticsbycategories",
                                         {'INPUT': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos de calor.gpkg'),
                                             'VALUES_FIELD_NAME': '', 'CATEGORIES_FIELD_NAME': ['NOME'],
                                             'OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos por Cidade.gpkg')})

            # Focos de Calor por Mesoregião HEAT POINTS FOR MESOREGIONS
            processing.runAndLoadResults("qgis:statisticsbycategories",
                                         {'INPUT': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos de calor.gpkg'),
                                             'VALUES_FIELD_NAME': '', 'CATEGORIES_FIELD_NAME': ['Região'],
                                             'OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos por Mesoregião.gpkg')})

            # Aplicar_Estilo para focos de calor APPLY STYLE FOR HEAT POINTS
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos de calor.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/focosdecalor.qml')})

            # Kernel KERNEL
            # Donwload_qml Kernel raster DOWNLOAD STYLE FOR KERNEL RASTER
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1IRoE-TNyS70WIOjzk3RPajGQBpOJtURx&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Areasprioritarias.qml')})

            # Analise de kernel KERNEL ANALYSIS
            processing.run("qgis:heatmapkerneldensityestimation",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Intensidade focos de calor.gpkg'),
                               'RADIUS': 0.2, 'RADIUS_FIELD': '', 'PIXEL_SIZE': 0.00778, 'WEIGHT_FIELD': '', 'KERNEL': 0,
                               'DECAY': 0, 'OUTPUT_VALUE': 0, 'OUTPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KERNEL.tif')})

            # Linhas do Kernel KERNEL LINES
            processing.run("gdal:contour",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KERNEL.tif'),
                               'BAND': 1,
                               'INTERVAL': 0.5, 'FIELD_NAME': 'SCORE', 'CREATE_3D': False, 'IGNORE_NODATA': False,
                               'NODATA': None, 'OFFSET': 0, 'EXTRA': '', 'OUTPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KernelLinhas.gpkg')})

           # Score Alto HIGHT SCORE
            processing.run("native:extractbyexpression",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KernelLinhas.gpkg'),
                               'EXPRESSION': 'Case when\r\nmean(\"SCORE\")*((mean(\"SCORE\")/median(\"SCORE\")))>=30\r\nthen\r\n\"SCORE\">mean(\"SCORE\")*((mean(\"SCORE\")/median(\"SCORE\")))\r\nelse\r\n\"SCORE\">= 30\r\nend',
                               'OUTPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCOREAlto.gpkg')})

            # mostrar mensagem SHOW MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Procurando por áreas prioritárias",
                level=Qgis.Info, duration=15)

            # Score Selecionado SELECTED SCORE
            processing.run("native:extractbyexpression",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCOREAlto.gpkg'),
                               'EXPRESSION': '\"SCORE\"=minimum(\"SCORE\")\r\n', 'OUTPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCORESelec.gpkg')})

            # Linha para Poligono LINES TO POLYGONS
            processing.run("qgis:linestopolygons",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCORESelec.gpkg'),
                               'OUTPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORE.gpkg')})

            # Centroides dos Poligonos CENTROID OF POLYGONS
            processing.run("native:centroids",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORE.gpkg'),
                               'ALL_PARTS': False,
                               'OUTPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORECentroides.gpkg')})

            # Intercessão Municipios_Centroides dos Poligonos INTERSECT COUNTIES WITH CENTROID
            processing.run("native:intersection", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORECentroides.gpkg'),
                'OVERLAY': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Limites municipais.gpkg'),
                'INPUT_FIELDS': [],
                'OVERLAY_FIELDS': [], 'OVERLAY_FIELDS_PREFIX': '', 'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroidsintersect.gpkg')})

            # Editar Campo Centroides ADJUST CENTROID FIELD
            processing.run("native:refactorfields", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroidsintersect.gpkg'),
                'FIELDS_MAPPING': [{'expression': '\"NOME\"', 'length': 0, 'name': 'NOME', 'precision': 0, 'type': 10},
                                   {'expression': '\"ESTADO\"', 'length': 0, 'name': 'ESTADO', 'precision': 0, 'type': 10},
                                   {'expression': '\"Região\"', 'length': 0, 'name': 'Região', 'precision': 0, 'type': 10},
                                   {'expression': 'to_dms($y,\'y\',2)', 'length': 20, 'name': 'Lat', 'precision': 0,
                                    'type': 10},
                                   {'expression': 'to_dms($x,\'x\',2)', 'length': 20, 'name': 'Long', 'precision': 0,
                                    'type': 10}], 'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroideEDITADO.gpkg')})

            # Associar atributo por local ACESS ATRIBUTES FOR LOCAL
            processing.run("native:joinattributesbylocation",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORE.gpkg'),
                               'JOIN': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroideEDITADO.gpkg'),
                               'PREDICATE': [0], 'JOIN_FIELDS': [], 'METHOD': 0, 'DISCARD_NONMATCHING': False, 'PREFIX': '',
                               'OUTPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREpronto.gpkg')})

            # Contagem Core_focos SCORE HEAT POINTS
            processing.run("native:countpointsinpolygon",
                           {'POLYGONS': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREpronto.gpkg'),
                               'POINTS': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos de calor.gpkg'),
                               'WEIGHT': '',
                               'CLASSFIELD': '', 'FIELD': 'NFocos', 'OUTPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Contagem.gpkg')})
            # Score>25 SCORE>25
            processing.run("native:extractbyexpression", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Contagem.gpkg'),
                'EXPRESSION': ' \"NFocos\">25', 'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREValido.gpkg')})

            # Areas Prioritarias PRIORITY AREAS
            processing.runAndLoadResults("native:refactorfields",
                                         {'INPUT': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREValido.gpkg'),
                                             'FIELDS_MAPPING': [
                                                 {'expression': '\"fid\"', 'length': 0, 'name': 'fid', 'precision': 0,
                                                  'type': 4},
                                                 {'expression': '\'ÁREA-\'||lpad(@row_number+1,2,0)', 'length': 10,
                                                  'name': 'Area_n',
                                                  'precision': 0, 'type': 10},
                                                 {'expression': '\"NOME\"', 'length': 0, 'name': 'NOME', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"ESTADO\"', 'length': 0, 'name': 'ESTADO', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"Região\"', 'length': 0, 'name': 'Região', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"Lat\"', 'length': 20, 'name': 'Lat', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"Long\"', 'length': 20, 'name': 'Long', 'precision': 0,
                                                  'type': 10},
                                                 {'expression': '\"NFocos\"', 'length': 0, 'name': 'NFocos', 'precision': 0,
                                                  'type': 6}],
                                             'OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Áreas Prioritárias.gpkg')})

            # Aplicar_Estilo para Áreas Prioritárias APPLY STYLE ON PRIORITY AREAS
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Áreas Prioritárias.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Areasprioritarias.qml')})

    ########################################################################################################################


            try:

                # Localizar situações FIND SITUANTIONS

                # mostrar mensagem SHOW MENSSAGER
                self.iface.messageBar().pushMessage(
                    "POLO", "Localizando situaçãoes de uso do fogo",
                    level=Qgis.Info, duration=15)

                # Downaload NOAAA - 20
                processing.run("native:filedownloader", {
                    'URL': 'https://firms.modaps.eosdis.nasa.gov/data/active_fire/noaa-20-viirs-c2/csv/J1_VIIRS_C2_South_America_7d.csv',
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA20.csv')})

                # Download NOAA - 21
                processing.run("native:filedownloader", {
                    'URL': 'https://firms.modaps.eosdis.nasa.gov/data/active_fire/noaa-21-viirs-c2/csv/J2_VIIRS_C2_South_America_7d.csv',
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA21.csv')})

                # Downlaod NOAA - S-NPP
                processing.run("native:filedownloader", {
                    'URL': 'https://firms.modaps.eosdis.nasa.gov/data/active_fire/suomi-npp-viirs-c2/csv/SUOMI_VIIRS_C2_South_America_7d.csv',
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_SNPP.csv')})

                # CSV para gpkg CSV TO GPKG
                # NOAA20
                processing.run("native:createpointslayerfromtable", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA20.csv'),
                    'XFIELD': 'longitude', 'YFIELD': 'latitude', 'ZFIELD': '', 'MFIELD': '',
                    'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'),
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA20.gpkg')})
                # NOAA21
                processing.run("native:createpointslayerfromtable", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA21.csv'),
                    'XFIELD': 'longitude', 'YFIELD': 'latitude', 'ZFIELD': '', 'MFIELD': '',
                    'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'),
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA21.gpkg')})
                # SNPP
                processing.run("native:createpointslayerfromtable", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_SNPP.csv'),
                    'XFIELD': 'longitude', 'YFIELD': 'latitude', 'ZFIELD': '', 'MFIELD': '',
                    'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'),
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_SNPP.gpkg')})

                NOAA20 = os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA20.gpkg')
                NOAA21 = os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_NOAA21.gpkg')
                SNPP = os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_SNPP.gpkg')

                processing.run("native:mergevectorlayers", {
                    'LAYERS': [NOAA20, NOAA21, SNPP],
                    'CRS': None,
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_SENSOR.gpkg')})

                # Intersect focos INTERSECT HEAT POINTS
                processing.runAndLoadResults("native:intersection",
                                             {'INPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/VIIRS_SENSOR.gpkg'),
                                                 'OVERLAY': os.path.expanduser(
                                                     '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Limites municipais.gpkg'),
                                                 'INPUT_FIELDS': [], 'OVERLAY_FIELDS': [], 'OVERLAY_FIELDS_PREFIX': '',
                                                 'OUTPUT': os.path.expanduser(
                                                     '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos de calor sensor VIIRS.gpkg')})

                # >>>>>>Estraindo O DIA

                processing.run("native:extractbyexpression", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Focos de calor sensor VIIRS.gpkg'),
                    'EXPRESSION': 'to_datetime(("acq_date" ||left("acq_time",2)||\':\'||right("acq_time",2)+\':00\'),\'yyyy-MM-ddhh:mm:ss\')>(now()-to_interval(\'12 hours\'))',
                    'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/situacao_data.gpkg')})

                # Kernel situações
                processing.run("qgis:heatmapkerneldensityestimation", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/situacao_data.gpkg'),
                    'RADIUS': 0.02, 'RADIUS_FIELD': '', 'PIXEL_SIZE': 0.002497, 'WEIGHT_FIELD': '', 'KERNEL': 0, 'DECAY': 0,
                    'OUTPUT_VALUE': 0, 'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KERNEL_VIIRS.tif')})

                # Linhas do kernel 6h

                processing.run("gdal:contour",
                               {'INPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KERNEL_VIIRS.tif'),
                                   'BAND': 1,
                                   'INTERVAL': 0.5, 'FIELD_NAME': 'SCORE', 'CREATE_3D': False, 'IGNORE_NODATA': False,
                                   'NODATA': None, 'OFFSET': 0, 'EXTRA': '', 'OUTPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KernelLinhasVIIRS.gpkg')})

                # Score Alto 6hrs HIGHT SCORE
                processing.run("native:extractbyexpression",
                               {'INPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/KernelLinhasVIIRS.gpkg'),
                                   'EXPRESSION': '\"SCORE\">mean(\"SCORE\")*((mean(\"SCORE\")/median(\"SCORE\")))',
                                   'OUTPUT': os.path.expanduser(
                                       '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCOREAlto24.gpkg')})

                # Score Selecionado SELECTED SCORE
                processing.run("native:extractbyexpression",
                               {'INPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCOREAlto24.gpkg'),
                                   'EXPRESSION': '\"SCORE\"=minimum(\"SCORE\")\r\n', 'OUTPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCORESelec24.gpkg')})

                # Linha para Poligono LINES TO POLYGONS
                processing.run("qgis:linestopolygons",
                               {'INPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/SCORESelec24.gpkg'),
                                   'OUTPUT': os.path.expanduser(
                                       '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORE24.gpkg')})

                # Centroides dos Poligonos CENTROID OF POLYGONS
                processing.run("native:centroids",
                               {'INPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORE24.gpkg'),
                                   'ALL_PARTS': False,
                                   'OUTPUT': os.path.expanduser(
                                       '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORECentroides_24.gpkg')})

                # Intercessão Municipios_Centroides dos Poligonos INTERSECT COUNTIES WITH CENTROID
                processing.run("native:intersection", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORECentroides_24.gpkg'),
                    'OVERLAY': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Limites municipais.gpkg'),
                    'INPUT_FIELDS': [],
                    'OVERLAY_FIELDS': [], 'OVERLAY_FIELDS_PREFIX': '', 'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroidsintersect_24.gpkg')})

                # Editar Campo Centroides ADJUST CENTROID FIELD
                processing.run("native:refactorfields", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroidsintersect_24.gpkg'),
                    'FIELDS_MAPPING': [{'expression': '\"NOME\"', 'length': 0, 'name': 'NOME', 'precision': 0, 'type': 10},
                                       {'expression': '\"ESTADO\"', 'length': 0, 'name': 'ESTADO', 'precision': 0,
                                        'type': 10},
                                       {'expression': '\"Região\"', 'length': 0, 'name': 'Região', 'precision': 0,
                                        'type': 10},
                                       {'expression': 'to_dms($y,\'y\',2)', 'length': 20, 'name': 'Lat', 'precision': 0,
                                        'type': 10},
                                       {'expression': 'to_dms($x,\'x\',2)', 'length': 20, 'name': 'Long', 'precision': 0,
                                        'type': 10}], 'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroideEDITADO_24.gpkg')})

                # Associar atributo por local ACESS ATRIBUTES FOR LOCAL
                processing.run("native:joinattributesbylocation",
                               {'INPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/CORE24.gpkg'),
                                   'JOIN': os.path.expanduser(
                                       '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/centroideEDITADO_24.gpkg'),
                                   'PREDICATE': [0], 'JOIN_FIELDS': [], 'METHOD': 0, 'DISCARD_NONMATCHING': False,
                                   'PREFIX': '',
                                   'OUTPUT': os.path.expanduser(
                                       '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREpronto_24.gpkg')})

                # Contagem Core_focos SCORE HEAT POINTS
                processing.run("native:countpointsinpolygon",
                               {'POLYGONS': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREpronto_24.gpkg'),
                                   'POINTS': os.path.expanduser(
                                       '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/situacao_data.gpkg'),
                                   'WEIGHT': '',
                                   'CLASSFIELD': '', 'FIELD': 'NFocos', 'OUTPUT': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Contagem_24.gpkg')})

                # Score>5
                processing.run("native:extractbyexpression", {
                    'INPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Contagem_24.gpkg'),
                    'EXPRESSION': ' \"NFocos\">=5', 'OUTPUT': os.path.expanduser(
                        '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREValido_24.gpkg')})

                # Areas Prioritarias PRIORITY AREAS
                processing.runAndLoadResults("native:refactorfields",
                                             {'INPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COREValido_24.gpkg'),
                                                 'FIELDS_MAPPING': [
                                                     {'expression': '\"fid\"', 'length': 0, 'name': 'fid', 'precision': 0,
                                                      'type': 4},
                                                     {'expression': '\'ÁREA-\'||lpad(@row_number+1,2,0)', 'length': 10,
                                                      'name': 'Area_n',
                                                      'precision': 0, 'type': 10},
                                                     {'expression': '\"NOME\"', 'length': 0, 'name': 'NOME', 'precision': 0,
                                                      'type': 10},
                                                     {'expression': '\"ESTADO\"', 'length': 0, 'name': 'ESTADO',
                                                      'precision': 0,
                                                      'type': 10},
                                                     {'expression': '\"Região\"', 'length': 0, 'name': 'Região',
                                                      'precision': 0,
                                                      'type': 10},
                                                     {'expression': '\"Lat\"', 'length': 20, 'name': 'Lat', 'precision': 0,
                                                      'type': 10},
                                                     {'expression': '\"Long\"', 'length': 20, 'name': 'Long',
                                                      'precision': 0,
                                                      'type': 10},
                                                     {'expression': '\"NFocos\"', 'length': 0, 'name': 'NFocos',
                                                      'precision': 0,
                                                      'type': 6}],
                                                 'OUTPUT': os.path.expanduser(
                                                     '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Situações de queimada.gpkg')})

            except Exception as e:
                # mostrar mensagem SHOW MENSSAGER
                self.iface.messageBar().pushMessage(
                    "POLO", "Não foram encontrada situações de queimadas",
                    level=Qgis.Info, duration=15)


    #######################################################################################################################
            # DASHBOARD
            # Donwload_qml Dashboard DONWLOAD STYLE DASHBOARD
            processing.run("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1PTiQKFOrlRPY4Yd6Vt_0KkyjoXJ5kk8O&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Dashboard_.qml')})

            # Donwload Dashboard DONWLOAD DASHBOARD
            processing.runAndLoadResults("native:filedownloader", {
                'URL': 'https://drive.google.com/u/0/uc?id=1NMSVdU1kqxGkVT2u1aYmuHiUM-jKO2wx&export=download',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/_Dashboard.gpkg')})
            processing.runAndLoadResults("qgis:checkvalidity",
                                         {'INPUT_LAYER': os.path.expanduser(
                                             '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/_Dashboard.gpkg'),
                                             'METHOD': 2, 'IGNORE_RING_SELF_INTERSECTION': False,
                                             'VALID_OUTPUT': os.path.expanduser(
                                                 '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Dashboard.gpkg')})

            # Aplicar_Estilo para Dashboard APPLY STYLE FOR DASHBOARD
            processing.run("native:setlayerstyle",
                           {'INPUT': os.path.expanduser(
                               '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Dashboard.gpkg'),
                               'STYLE': os.path.expanduser(
                                   '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Dashboard_.qml')})


            #Historico INPE HISTORIC INPE

            # mostrar mensagem SHOW MENSSAGER
            self.iface.messageBar().pushMessage(
                "POLO", "Acessando dados de históricos do INPE",
                level=Qgis.Info, duration=15)

            # Donwload historico amazonas DONWLOAD AMAZON HISTORIC
            processing.runAndLoadResults("native:filedownloader", {
                'URL': 'https://terrabrasilis.dpi.inpe.br/queimadas/situacao-atual/media/estado/csv_estatisticas/historico_estado_amazonas.csv',
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Historico Amazonas.csv')})

            processing.run("native:refactorfields", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Historico Amazonas.csv'),
                'FIELDS_MAPPING': [
                    {'expression': '"field_1"', 'length': 0, 'name': 'field_1', 'precision': 0, 'sub_type': 0, 'type': 10,
                     'type_name': 'text'},
                    {'expression': 'replace("Janeiro",\'-\',\'0\')', 'length': 0, 'name': 'Janeiro', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Fevereiro",\'-\',\'0\')', 'length': 0, 'name': 'Fevereiro', 'precision': 0,
                     'sub_type': 10,
                     'type': 4, 'type_name': 'text'},
                    {'expression': 'replace("MarÃ§o",\'-\',\'0\')', 'length': 0, 'name': 'Março', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Abril",\'-\',\'0\')', 'length': 0, 'name': 'Abril', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Maio",\'-\',\'0\')', 'length': 0, 'name': 'Maio', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Junho",\'-\',\'0\')', 'length': 0, 'name': 'Junho', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Julho",\'-\',\'0\')', 'length': 0, 'name': 'Julho', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Agosto",\'-\',\'0\')', 'length': 0, 'name': 'Agosto', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Setembro",\'-\',\'0\')', 'length': 0, 'name': 'Setembro', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Outubro",\'-\',\'0\')', 'length': 0, 'name': 'Outubro', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Novembro",\'-\',\'0\')', 'length': 0, 'name': 'Novembro', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Dezembro",\'-\',\'0\')', 'length': 0, 'name': 'Dezembro', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'},
                    {'expression': 'replace("Total",\'-\',\'0\')', 'length': 0, 'name': 'Total', 'precision': 0,
                     'sub_type': 10, 'type': 4,
                     'type_name': 'text'}]
                ,
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Historico_Amazonas.csv')})

            # Historico mês
            processing.run("native:extractbyexpression",
                            {'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Historico_Amazonas.csv'),
                'EXPRESSION': 'to_real("field_1")>1',
                             'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Select_Historico_AM.csv')})

            processing.run("native:orderbyexpression", {
                'INPUT':os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Select_Historico_AM.csv') ,
                'EXPRESSION': "lpad(eval(title(format_date(now(),'MMMM'))),7,0)", 'ASCENDING': False, 'NULLS_FIRST': False, 'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/ORDEM_Historico_AM.csv')})



            #Historico anos
            processing.run("native:orderbyexpression", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Select_Historico_AM.csv'),
                'EXPRESSION':'lpad("Total",7,0)', 'ASCENDING': False, 'NULLS_FIRST': False,
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Ordem_anos_AM.gpkg')})


            # Abrir projeto do relatorio OPEN REPORT PROJECT
            project = QgsProject.instance()
            project.read(os.path.expanduser('~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/POLO.QGZ'))
            print(project.fileName())


            # Exportar relatório EXPORT REPORT
            folder_path = self.dlg.localsave.filePath()

            DATANAME = datetime.now().strftime("%d_%m_%y")
            LOCAL = os.path.join(folder_path, 'Relatorio_' + DATANAME + '.pdf')
            LOCALFILE = os.path.join(folder_path)

            processing.run("native:printlayouttopdf",
                           {'LAYOUT': 'Relatório Focos de Calor', 'LAYERS': None, 'DPI': None, 'FORCE_VECTOR': False,
                            'GEOREFERENCE': True, 'INCLUDE_METADATA': True, 'DISABLE_TILED': False, 'SIMPLIFY': True,
                            'TEXT_FORMAT': 0, 'SEPARATE_LAYERS': False,
                            'OUTPUT': LOCAL})

            #Exportar areas prioritarias EXPORT PRIORITY AREAS

            processing.run("native:atlaslayouttomultiplepdf",
                           {'LAYOUT': 'Mapas das Áreas Prioritárias', 'COVERAGE_LAYER': None, 'FILTER_EXPRESSION': '',
                            'SORTBY_EXPRESSION': '', 'SORTBY_REVERSE': False, 'LAYERS': None, 'DPI': None,
                            'FORCE_VECTOR': False, 'FORCE_RASTER': False, 'GEOREFERENCE': True, 'INCLUDE_METADATA': True,
                            'DISABLE_TILED': False, 'SIMPLIFY': True, 'TEXT_FORMAT': 0, 'IMAGE_COMPRESSION': 0,
                            'OUTPUT_FILENAME': '"Area_n"||\'_\'||upper("NOME")||\'_\'||format_date(now(),\'dd_MM_yyyy\')\r\n',
                            'OUTPUT_FOLDER': LOCALFILE})

            # Exportar situação de uso do fogo EXPORT FIRE LOCATION

            processing.run("native:atlaslayouttomultiplepdf",
                           {'LAYOUT': 'Mapa de Situações de Uso do Fogo', 'COVERAGE_LAYER': None, 'FILTER_EXPRESSION': '',
                            'SORTBY_EXPRESSION': '', 'SORTBY_REVERSE': False, 'LAYERS': None, 'DPI': None,
                            'FORCE_VECTOR': False, 'FORCE_RASTER': False, 'GEOREFERENCE': True, 'INCLUDE_METADATA': True,
                            'DISABLE_TILED': False, 'SIMPLIFY': True, 'TEXT_FORMAT': 0, 'IMAGE_COMPRESSION': 0,
                            'OUTPUT_FILENAME': '"nome"||\'_situação n\'||right("area_n",2)',
                            'OUTPUT_FOLDER': LOCALFILE})
            """
            #Colocação do Mês ao longo dos anos
            processing.runAndLoadResults("native:refactorfields", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Ordem_Historico_AM.csv'),
                'FIELDS_MAPPING': [
                    {'expression': '"field_1"', 'length': 0, 'name': 'field_1', 'precision': 0, 'sub_type': 0, 'type': 10,
                     'type_name': 'text'},
                    {'expression': '"Janeiro"', 'length': 0, 'name': 'Janeiro', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Fevereiro"', 'length': 0, 'name': 'Fevereiro', 'precision': 0, 'sub_type': 0,
                     'type': 4, 'type_name': 'text'},
                    {'expression': '"MarÃƒÆ’Ã‚Â§o"', 'length': 0, 'name': 'Março', 'precision': 0, 'sub_type': 0,
                     'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Abril"', 'length': 0, 'name': 'Abril', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Maio"', 'length': 0, 'name': 'Maio', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Junho"', 'length': 0, 'name': 'Junho', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Julho"', 'length': 0, 'name': 'Julho', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Agosto"', 'length': 0, 'name': 'Agosto', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Setembro"', 'length': 0, 'name': 'Setembro', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Outubro"', 'length': 0, 'name': 'Outubro', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Novembro"', 'length': 0, 'name': 'Novembro', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Dezembro"', 'length': 0, 'name': 'Dezembro', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '"Total"', 'length': 0, 'name': 'Total', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '@row_number+1 ', 'length': 0, 'name': 'POS', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'int8'}],
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/POS_MES.gpkg')})
    
            #Classificação do pior Mês
            processing.runAndLoadResults("native:refactorfields", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/Ordem_anos_AM.gpkg'),
                'FIELDS_MAPPING': [
                    {'expression': '"field_1"', 'length': 0, 'name': 'field_1', 'precision': 0, 'sub_type': 0, 'type': 10,
                     'type_name': 'text'},
                    {'expression': '"Total"', 'length': 0, 'name': 'Total', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '@row_number+1', 'length': 0, 'name': 'POS', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'int8'}],
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/POS_ANO.gpkg')})
    
            #Valores dos meses corrrente
            processing.run("native:refactorfields", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/POS_MES.gpkg'),
                'FIELDS_MAPPING': [
                    {'expression': '"field_1"', 'length': 0, 'name': 'field_1', 'precision': 0, 'sub_type': 0, 'type': 10,
                     'type_name': 'text'}, {
                        'expression': 'lpad(with_variable(\'MES\',format_date(now(),\'MM\'),\r\nCase\r\n\twhen @MES = 1 then "Janeiro"\r\n\twhen @MES = 2 then "Janeiro"+"Fevereiro"\r\n\twhen @MES = 3 then "Janeiro"+"Fevereiro"+"Março"\r\n\twhen @MES = 4 then "Janeiro"+"Fevereiro"+"Março"+"Abril"\r\n\twhen @MES = 5 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"\r\n\twhen @MES = 6 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"+"Junho"\r\n\twhen @MES = 7 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"+"Junho"+"Julho"\r\n\twhen @MES = 8 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"+"Junho"+"Julho"+"Agosto"\r\n\twhen @MES = 9 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"+"Junho"+"Julho"+"Agosto"+"Setembro"\r\n\twhen @MES = 10 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"+"Junho"+"Julho"+"Agosto"+"Setembro"+"Outubro"\r\n\twhen @MES = 11 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"+"Junho"+"Julho"+"Agosto"+"Setembro"+"Outubro"+"Novembro"\r\n\twhen @MES = 12 then "Janeiro"+"Fevereiro"+"Março"+"Abril"+"Maio"+"Junho"+"Julho"+"Agosto"+"Setembro"+"Outubro"+"Novembro"+"Dezembro"\r\nelse \'ERRO\'\r\nend\r\n),5,0)',
                        'length': 0, 'name': 'AC_ANO', 'precision': 0, 'sub_type': 0, 'type': 4, 'type_name': 'int8'}],
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COR_ANO.csv')})
    
            #qualificação meses corrente
            processing.run("native:orderbyexpression", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COR_ANO.csv'),
                'EXPRESSION': 'lpad("AC_ANO",7,0)', 'ASCENDING': False, 'NULLS_FIRST': False,
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/QUALI_ANO.gpkg')})
    
            # Classificação do pior Mês
            processing.runAndLoadResults("native:refactorfields", {
                'INPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/QUALI_ANO.gpkg'),
                'FIELDS_MAPPING': [
                    {'expression': '"field_1"', 'length': 0, 'name': 'field_1', 'precision': 0, 'sub_type': 0, 'type': 10,
                     'type_name': 'text'},
                    {'expression': '"AC_ANO"', 'length': 0, 'name': 'Total', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'text'},
                    {'expression': '@row_number+1', 'length': 0, 'name': 'POS', 'precision': 0, 'sub_type': 0, 'type': 4,
                     'type_name': 'int8'}],
                'OUTPUT': os.path.expanduser(
                    '~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/polo/Process/COR_ANO.gpkg')})
            """
            # SHOW FINISH MENSSEGER
            self.iface.messageBar().pushMessage(
                "POLO", "Sucesso o processamento terminou " + LOCAL,
                level=Qgis.Success, duration=30)
