# -*- coding: utf-8 -*-
"""
/***************************************************************************
 INDE
                                 A QGIS plugin
 This plugin allows connection to all ows services available in Brazil National Spatial Data Infrastructure
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-10-26
        git sha              : $Format:%H$
        copyright            : (C) 2020 by Julierme G Pinheiro / Leandro França
        email                : contato@geoone.com.br
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt, QUrl
from qgis.PyQt.QtGui import QIcon, QCursor, QDesktopServices
from qgis.PyQt.QtWidgets import QAction, QMainWindow, QApplication, QLabel, QMessageBox, QAbstractItemView

# from PyQt5.QtGui import QDesktopServices
# Initialize Qt resources from file resources.py
from .resources import *
from .INDE_urls import InstLista, InstDic
# Import the code for the dialog
from .INDE_dialog import INDEDialog
import os.path

# Helper p/ enum
EXTENDED_SEL = getattr(getattr(QAbstractItemView, "SelectionMode", QAbstractItemView), "ExtendedSelection")
CURSOR_POINTING = getattr(getattr(Qt, "CursorShape", Qt), "PointingHandCursor", getattr(Qt, "PointingHandCursor", None))


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

        # 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('INDE', 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.addWebToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToWebMenu(
                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/INDE/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'INDE'),
            callback=self.run,
            parent=self.iface.mainWindow())

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

    def msg_exec(self, msg):
        try:
            return msg.exec()     # PyQt6
        except AttributeError:
            return msg.exec_()    # PyQt5


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

    def noService(self, ogc, institution):
        msg = QMessageBox()
        msg.setWindowTitle('No Service')
        msg.setText('No ' + ogc + ' available for ' + institution)
        msg.setIcon(QMessageBox.Information)
        self.msg_exec(msg)

    def institutionOWSService(self, ogc, institution):

        msg = QMessageBox()
        msg.setWindowTitle(institution + ' ' + ogc + ' services')
        msg.setText(ogc + ' connections for ' + institution +
                    ' available in: href="https://acervofundiario.incra.gov.br/acervo/ogc.php')
        msg.setIcon(QMessageBox.Information)
        self.msg_exec(msg)

    def removeItemsWarning(self):
        msg = QMessageBox()
        msg.setWindowTitle('Remove Items')
        msg.setText('You must select an item to be removed')
        msg.setIcon(QMessageBox.Information)
        msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
        msg.setDetailedText(
            'You have not selected any item to be removed. Please do so.')
        msg.setDefaultButton(QMessageBox.Ok)
        self.msg_exec(msg)

    def addAllItems(self, items, id):
        if id == 0:
            self.dlg.listWidgetSelectedInstitutions.clear()
            self.dlg.listWidgetSelectedInstitutions.addItems(items)
        else:
            self.dlg.listWidgetSelectedBasemaps.clear()
            self.dlg.listWidgetSelectedBasemaps.addItems(items)

    def populatelistWidget(self, items, id):
        if id == 0:
            self.dlg.listWidgetInstitutionAvailableWMS.clear()
            self.dlg.listWidgetInstitutionAvailableWMS.addItems(items)
        # setting selection mode property
        # (2 = QAbstractItemView.MultiSelection)
        # (3 = QAbstractItemView.ExtendedSelection)
        # (4 = QAbstractItemView.ContiguousSelection)
            self.dlg.listWidgetInstitutionAvailableWMS.setSelectionMode(EXTENDED_SEL)
        else:
            self.dlg.listWidgetBasemapList.clear()
            self.dlg.listWidgetBasemapList.addItems(items)
            self.dlg.listWidgetBasemapList.setSelectionMode(EXTENDED_SEL)

    def addSelectedItems(self, id):
        if id == 0:
            itemsSelected = self.dlg.listWidgetInstitutionAvailableWMS.selectedItems()
            numberSelectedElements = len(itemsSelected)
            if (numberSelectedElements == 0):
                msg = QMessageBox()
                msg.setWindowTitle('Add Items')
                msg.setText('You must select an item to be added')
                msg.setIcon(QMessageBox.Information)
                msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
                msg.setDetailedText(
                    'You have not selected any item to be added. Please do so.')
                msg.setDefaultButton(QMessageBox.Ok)
                self.msg_exec(msg)
            else:
                x = []
                x.clear()
                for i in range(len(itemsSelected)):
                    x.append(itemsSelected[i].text())
                self.dlg.listWidgetSelectedInstitutions.clear()
                self.dlg.listWidgetSelectedInstitutions.addItems(x)
        else:
            itemsSelected = self.dlg.listWidgetBasemapList.selectedItems()
            numberSelectedElements = len(itemsSelected)
            if (numberSelectedElements == 0):
                msg = QMessageBox()
                msg.setWindowTitle('Add Items')
                msg.setText('You must select an item to be added')
                msg.setIcon(QMessageBox.Information)
                msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
                msg.setDetailedText(
                    'You have not selected any item to be added. Please do so.')
                msg.setDefaultButton(QMessageBox.Ok)
                self.msg_exec(msg)
            else:
                x = []
                x.clear()
                # self.iface.reloadConnections()
                for i in range(len(itemsSelected)):
                    x.append(itemsSelected[i].text())
                self.dlg.listWidgetSelectedBasemaps.clear()
                self.dlg.listWidgetSelectedBasemaps.addItems(x)

    def removeSelectedItems(self, id):
        if id == 0:
            itemsSelected = self.dlg.listWidgetSelectedInstitutions.selectedItems()
            numberSelectedElements = len(itemsSelected)
            if (numberSelectedElements == 0):
                msg = QMessageBox()
                msg.setWindowTitle('Remove Items')
                msg.setText('You must select an item to be removed')
                msg.setIcon(QMessageBox.Information)
                msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
                msg.setDetailedText(
                    'You have not selected any item to be removed. Please do so.')
                msg.setDefaultButton(QMessageBox.Ok)
                self.msg_exec(msg)
            else:
                for i in itemsSelected:
                    self.dlg.listWidgetSelectedInstitutions.takeItem(
                        self.dlg.listWidgetSelectedInstitutions.row(i))
        else:
            itemsSelected = self.dlg.listWidgetSelectedBasemaps.selectedItems()
            numberSelectedElements = len(itemsSelected)
            if (numberSelectedElements == 0):
                msg = QMessageBox()
                msg.setWindowTitle('Remove Items')
                msg.setText('You must select an item to be removed')
                msg.setIcon(QMessageBox.Information)
                msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
                msg.setDetailedText(
                    'You have not selected any item to be removed. Please do so.')
                msg.setDefaultButton(QMessageBox.Ok)
                self.msg_exec(msg)
            else:
                for i in itemsSelected:
                    self.dlg.listWidgetSelectedBasemaps.takeItem(
                        self.dlg.listWidgetSelectedBasemaps.row(i))

    def removeAllItems(self, id):
        if id == 0:
            self.dlg.listWidgetSelectedInstitutions.clear()
        else:
            self.dlg.listWidgetSelectedBasemaps.clear()

    def setOwsConnection(self, sdi, connectionList):
        # connection type, connection name,  authcfg, password, referer, url, username, zmax, zmin
        for obj in connectionList:
            cType = obj.connectionType
            cName = obj.connectionName
            cUrl = obj.connectionUrl
            if 'wms' == cType:
                base_path = f"connections/ows/items/wms/connections/items/{cName}"
                sdi.setValue(f"{base_path}/url", cUrl)
                sdi.setValue(f"{base_path}/username", "")
                sdi.setValue(f"{base_path}/password", "")
                sdi.setValue(f"{base_path}/http-header", "{{}}")
                sdi.setValue(f"{base_path}/ignore-axis-orientation", False)
                sdi.setValue(f"{base_path}/invert-axis-orientation", False)
                sdi.setValue(f"{base_path}/smooth-pixmap-transform", False)
                sdi.setValue(f"{base_path}/tile-pixel-ratio", 0)
                sdi.setValue(f"{base_path}/dpi-mode", 7)
                sdi.setValue(f"{base_path}/ignore-get-feature-info-uri", False)
                sdi.setValue(f"{base_path}/ignore-get-map-uri", False)
                sdi.setValue(f"{base_path}/reported-layer-extents", False)
            elif 'wfs' == cType:
                base_path = f"connections/ows/items/wfs/connections/items/{cName}"
                sdi.setValue(f"{base_path}/url", cUrl)
                sdi.setValue(f"{base_path}/username", "")
                sdi.setValue(f"{base_path}/password", "")
                sdi.setValue(f"{base_path}/http-header", "{{}}")
                sdi.setValue(f"{base_path}/ignore-axis-orientation", False)
            elif 'wcs' == cType:
                base_path = f"connections/ows/items/wcs/connections/items/{cName}"
                sdi.setValue(f"{base_path}/url", cUrl)
                sdi.setValue(f"{base_path}/username", "")
                sdi.setValue(f"{base_path}/password", "")
                sdi.setValue(f"{base_path}/http-header", "{{}}")
                sdi.setValue(f"{base_path}/ignore-axis-orientation", False)
            elif 'xyz' == cType:
                base_path = f"connections/xyz/items/{cName}"
                sdi.setValue(f"{base_path}/url", cUrl)
                sdi.setValue(f"{base_path}/http-header", "{'referer': ''}")
                sdi.setValue(f"{base_path}/zmax", 22) # Zoom máximo
                sdi.setValue(f"{base_path}/zmin", 0) # Zoom mínimo
                
            # sdi.setValue("qgis/%s/%s/authcfg" %
            #              (cType, cName), obj.connectionAuthcfg)
            # sdi.setValue('qgis/%s/%s/password' %
            #              (cType, cName), obj.connectionPassword)
            # sdi.setValue("connections/ows/items/%s/connections/items/%s/http-header" %
            #              (cType, cName), obj.connectionReferer)
            # sdi.setValue("connections/ows/items/%s/connections/items/%s/url" % (cType, cName), obj.connectionUrl)
            # sdi.setValue("connections/ows/items/%s/connections/items/%s/username" %
            #              (cType, cName), obj.connectionUsername)
            # sdi.setValue("connections/xyz/items/%s/zmax" %
            #              (cType, cName), obj.connectionZmax)
            # sdi.setValue("connections/xyz/items/%s/zmin" %
            #              (cType, cName), obj.connectionZmin)
        self.iface.reloadConnections()

    def addWmsConnection(self, ogc, sdi, connectionList, connectionAtributtes):

        itemsToBeAdd = []
        connectionList.clear()

        for i in range(self.dlg.listWidgetSelectedInstitutions.count()):
            itemsToBeAdd.append(
                self.dlg.listWidgetSelectedInstitutions.item(i).text())

        for instituicao in InstDic:
            if instituicao in itemsToBeAdd:
                if not InstDic[instituicao]['wmsAvailable']:
                    self.noService(ogc, instituicao)
                else:
                    connectionList.append(connectionAtributtes(ogc, instituicao, "", "", "",InstDic[instituicao]['url'], "", "22", "0"))

        if 'AESA_PB' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "AESA_PB", "", "", "",
                                                       "http://siegrh.aesa.pb.gov.br:8080/geoserver/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'ANA_AQUACOOPE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ANA_AQUACOOPE", "", "", "",
                                                       "https://www.aquacoope.org/geoserver/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'CPRM_SACE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CPRM_SACE", "", "", "",
                                                       "http://sace.cprm.gov.br/geoserver/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'DPC' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "DPC", "", "", "",
                                                       "https://geoservicos.inde.gov.br/geoserver/DPC/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'INCRA' in itemsToBeAdd:
            institution = 'INCRA'
            self.institutionOWSService(ogc, institution)
        
        if 'INPE_CBERS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "INPE_CBERS", "", "", "",
                                                       "http://www.dpi.inpe.br/fipcerrado-geoserver/ows/wms?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'INPE FOCOS DE CALOR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "INPE FOCOS DE CALOR", "", "", "",
                                                       "http://queimadas.dgi.inpe.br/queimadas/mapas/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'PEM' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "PEM", "", "", "",
                                                       "https://geoservicos.inde.gov.br/geoserver/PEM/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'SFB_CAR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "SFB_CAR", "", "", "",
                                                       "https://geoserver.car.gov.br/geoserver/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'CELEPAR_PR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CELEPAR_PR", "", "", "",
                                                       "http://geoserver.pr.gov.br/geoserver/ows?service=wms&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        if 'IDE_BA' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "IDE_BA", "", "", "",
                                                       "http://servicos.geo.sei.ba.gov.br/bahia_cart_100k_7080/WMTS", "", "22", "0"))

        self.setOwsConnection(sdi, connectionList)

    def addWfsConnection(self, ogc, sdi, connectionList, connectionAtributtes):

        itemsToBeAdd = []
        connectionList.clear()

        for i in range(self.dlg.listWidgetSelectedInstitutions.count()):
            itemsToBeAdd.append(
                self.dlg.listWidgetSelectedInstitutions.item(i).text())

        for instituicao in InstDic:
            if instituicao in itemsToBeAdd:
                if not InstDic[instituicao]['wfsAvailable']:
                    self.noService(ogc, instituicao)
                else:
                    connectionList.append(connectionAtributtes(ogc, instituicao, "", "", "",InstDic[instituicao]['url'], "", "22", "0"))


        if 'AESA_PB' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "AESA_PB", "", "", "",
                                                       "http://siegrh.aesa.pb.gov.br:8080/geoserver/ows?service=wfs&version=2.0.0&request=GetCapabilities", "", "22", "0"))

        if 'ANA_AQUACOOPE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ANA_AQUACOOPE", "", "", "",
                                                       "https://www.aquacoope.org/geoserver/ows?service=wfs&version=2.0.0&request=GetCapabilities", "", "22", "0"))

        if 'CPRM_SACE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CPRM_SACE", "", "", "",
                                                       "https://geoservicos.cprm.gov.br/geoserver/geologia/ows/?service=wfs&version=2.0.0&request=GetCapabilities", "", "22", "0"))

        if 'DPC' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "DPC", "", "", "",
                                                       "https://geoservicos.inde.gov.br/geoserver/DPC/ows?service=wfs&version=2.0.0&request=GetCapabilities", "", "22", "0"))

        if 'INPE_CBERS' in itemsToBeAdd:
            institution = 'INPE_CBERS'
            self.noService(ogc, institution)

        if 'INPE FOCOS DE CALOR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "INPE FOCOS DE CALOR", "", "", "",
                                                       "http://queimadas.dgi.inpe.br/queimadas/mapas/ows?service=wfs&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        
        if 'PEM' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "PEM", "", "", "",
                                                       "https://geoservicos.inde.gov.br/geoserver/PEM/ows?service=wfs&version=2.0.0&request=GetCapabilities", "", "22", "0"))

        if 'SFB_CAR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "SFB_CAR", "", "", "",
                                                       "https://geoserver.car.gov.br/geoserver/ows?service=wfs&version=2.0.0&request=GetCapabilities", "", "22", "0"))

        if 'CELEPAR_PR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CELEPAR_PR", "", "", "",
                                                       "http://geoserver.pr.gov.br/geoserver/ows?service=wfs&version=1.3.0&request=GetCapabilities", "", "22", "0"))
        
        if 'IDE_BA' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_SANEAMENTO", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_abastecimento_saneamento", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_ADMINISTRACAO", "", "", "",
                                                       "http://servicos.geo.sei.ba.gov.br/wfs/cb_100k_administracao_publica", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_EDIFICACOES", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_edificacoes", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_EDU_CULTURA", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_educacao_cultura", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_ENERGIA", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_energia_comunicacoes", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_ESTRUTURA", "", "", "",
                                                       "http://servicos.geo.sei.ba.gov.br/wfs/cb_100k_estrutura_economica", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_HIDROGRAFIA", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_hidrografia", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_LIMITES", "", "", "",
                                                       "http://servicos.geo.sei.ba.gov.br/wfs/cb_100k_limites", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_LOCALIDADES", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_localidades", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_REFERENCIA", "", "", "",
                                                       "http://servicos.geo.sei.ba.gov.br/wfs/cb_100k_pontos_referencia", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_RELEVO", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_relevo", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_SAUDE", "", "", "",
                                                       "http://servicos.geo.sei.ba.gov.br/wfs/cb_100k_saude_serv_social", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_TRANSPORTE", "", "", "",
                                                       "https://servicos.geo.sei.ba.gov.br/wfs/cb_100k_sistema_transporte", "", "22", "0"))
            connectionList.append(connectionAtributtes(ogc, "IDE_BA_VEGETACAO", "", "", "",
                                                       "http://servicos.geo.sei.ba.gov.br/wfs/cb_100k_vegetacao", "", "22", "0"))

        if 'INCRA' in itemsToBeAdd:
            institution = 'INCRA'
            self.institutionOWSService(ogc, institution)

        self.setOwsConnection(sdi, connectionList)


    def addWcsConnection(self, ogc, sdi, connectionList, connectionAtributtes):

        itemsToBeAdd = []
        connectionList.clear()

        for i in range(self.dlg.listWidgetSelectedInstitutions.count()):
            itemsToBeAdd.append(
                self.dlg.listWidgetSelectedInstitutions.item(i).text())

        for instituicao in InstDic:
            if instituicao in itemsToBeAdd:
                if not InstDic[instituicao]['wcsAvailable']:
                    self.noService(ogc, instituicao)
                else:
                    connectionList.append(connectionAtributtes(ogc, instituicao, "", "", "",InstDic[instituicao]['url'], "", "22", "0"))

        if 'AESA_PB' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "AESA_PB", "", "", "",
                                                       "http://siegrh.aesa.pb.gov.br:8080/geoserver/ows?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))

        if 'ANA_AQUACOOPE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ANA_AQUACOOPE", "", "", "",
                                                       "https://www.aquacoope.org/geoserver/ows?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))
        if 'CPRM_SACE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CPRM_SACE", "", "", "",
                                                       "https://geoservicos.cprm.gov.br/geoserver/geologia/ows/?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))
        if 'DPC' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "DPC", "", "", "",
                                                       "https://geoservicos.inde.gov.br/geoserver/DPC/ows?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))

        if 'IDE_BA' in itemsToBeAdd:
            institution = 'IDE_BA'
            self.noService(ogc, institution)

        if 'INPE FOCOS DE CALOR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "INPE FOCOS DE CALOR", "", "", "",
                                                       "http://queimadas.dgi.inpe.br/queimadas/mapas/ows?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))

        if 'INPE_CBERS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "INPE_CBERS", "", "", "",
                                                       "http://www.dpi.inpe.br/fipcerrado-geoserver/ows/wms?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))

        if 'INCRA' in itemsToBeAdd:
            institution = 'INCRA'
            self.institutionOWSService(ogc, institution)
        
        if 'CELEPAR_PR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CELEPAR_PR", "", "", "",
                                                       "http://geoserver.pr.gov.br/geoserver/ows?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))
        
        if 'SFB_CAR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "SFB_CAR", "", "", "",
                                                       "https://geoserver.car.gov.br/geoserver/ows?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))

        if 'PEM' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "PEM", "", "", "",
                                                       "https://geoservicos.inde.gov.br/geoserver/PEM/ows?service=WCS&version=2.0.1&request=GetCapabilities", "", "22", "0"))

        self.setOwsConnection(sdi, connectionList)

    # def getGroupXYZ(self, ogc, sdi):
        # ows_service = 'qgis/' + ogc
        # sdi.beginGroup(ows_service)
        # groupsXYZ = sdi.childGroups()
        # sdi.endGroup()
        # return groupsXYZ

    def addXyzConnection(self, ogc, sdi, connectionList, connectionAtributtes):

        itemsToBeAdd = []
        connectionList.clear()

        for i in range(self.dlg.listWidgetSelectedBasemaps.count()):
            itemsToBeAdd.append(
                self.dlg.listWidgetSelectedBasemaps.item(i).text())

        if 'SENTINEL-2' in itemsToBeAdd:
            ogc = 'wms'
            connectionList.append(connectionAtributtes(ogc, "SENTINEL-2", "", "", "",
                                                       "https://tiles.maps.eox.at/wmts?SERVICE=WMTS&REQUEST=GetCapabilities", "", "22", "0"))
            ogc = 'xyz'
        if 'OSM STANDARD' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM STANDARD", "", "", "",
                                                       "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM OPENTOPOMAP' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM OPENTOPOMAP", "", "", "",
                                                       "https://a.tile.opentopomap.org/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM HOT' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM HOT", "", "", "",
                                                       "https://a.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM DEUTSCHLAND' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM DEUTSCHLAND", "", "", "",
                                                       "https://a.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM SWITZERLAND' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM SWITZERLAND", "", "", "",
                                                       "https://tile.osm.ch/switzerland/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM FRANCE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM FRANCE", "", "", "",
                                                       "https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM BREZHONEG' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM BREZHONEG", "", "", "",
                                                       "https://tile.openstreetmap.bzh/br/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM VELOROAD' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM VELOROAD", "", "", "",
                                                       "http://tile.osmz.ru/veloroad/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM TRACKS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM TRACKS", "", "", "",
                                                       "http://gps-a.tile.openstreetmap.org/lines/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM MONOCHROME' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM MONOCHROME", "", "", "",
                                                       "http://a.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM HIKE & BIKE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM HIKE & BIKE", "", "", "",
                                                       "https://tiles.wmflabs.org/hikebike/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM HILLSHADING' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM HILLSHADING", "", "", "",
                                                       "http://tiles.wmflabs.org/hillshading/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM GRAYSCALE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM GRAYSCALE", "", "", "",
                                                       "https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png", "", "22", "0"))
        if 'OSM NO LABELS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OSM NO LABELS", "", "", "",
                                                       "https://tiles.wmflabs.org/osm-no-labels/{z}/{x}/{y}.png", "", "22", "0"))

        if 'GOOGLE SATELLITE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE SATELLITE", "", "", "",
                                                       "https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE TERRAIN' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE TERRAIN", "", "", "",
                                                       "https://mt1.google.com/vt/lyrs=t&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE TERRAIN HYBRID' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE TERRAIN HYBRID", "", "", "",
                                                       "https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE SATELLITE HYBRID' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE SATELLITE HYBRID", "", "", "",
                                                       "https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE TRAFFIC' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE TRAFFIC", "", "", "",
                                                       "https://mt1.google.com/vt?lyrs=h@159000000,traffic|seconds_into_week:-1&style=3&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE ROAD' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE ROAD", "", "", "",
                                                       "https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE MAPS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE MAPS", "", "", "",
                                                       "https://mt1.google.com/vt/lyrs=r&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE NORMAL' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE NORMAL", "", "", "",
                                                       "http://www.google.cn/maps/vt?lyrs=m@189&gl=cn&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'GOOGLE SAT' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "GOOGLE SAT", "", "", "",
                                                       "http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}", "", "22", "0"))
        if 'ESRI BOUNDARIES PLACES' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI BOUNDARIES PLACES", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI GRAY DARK' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI GRAY DARK", "", "", "",
                                                       "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x", "", "22", "0"))
        if 'ESRI GRAY LIGHT' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI GRAY LIGHT", "", "", "",
                                                       "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI NATIONAL GEOGRAPHIC' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI NATIONAL GEOGRAPHIC", "", "", "",
                                                       "http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI OCEAN' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI OCEAN", "", "", "",
                                                       "https://services.arcgisonline.com/ArcGIS/rest/services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI PHYSICAL' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI PHYSICAL", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI REFERENCE OVERLAY' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI REFERENCE OVERLAY", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Reference_Overlay/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI SATELLITE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI SATELLITE", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI WORLD IMAGERY' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI WORLD IMAGERY", "", "", "",
                                                       "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI SHADED RELIEF' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI SHADED RELIEF", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI STANDARD' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI STANDARD", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI TERRAIN' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI TERRAIN ", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI WORLD TOPO' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI WORLD TOPO", "", "", "",
                                                       "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'ESRI TRANSPORTATION' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "ESRI TRANSPORTATION", "", "", "",
                                                       "https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer/tile/{z}/{y}/{x}", "", "22", "0"))
        if 'STAMEN TERRAIN' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TERRAIN", "", "", "",
                                                       "http://a.tile.stamen.com/terrain/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TERRAIN BACKGROUND' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TERRAIN BACKGROUND", "", "", "",
                                                       "http://a.tile.stamen.com/terrain-background/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TERRAIN LABELS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TERRAIN LABELS", "", "", "",
                                                       "http://a.tile.stamen.com/terrain-labels/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TERRAIN LINES' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TERRAIN LINES", "", "", "",
                                                       "http://a.tile.stamen.com/terrain-lines/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TONER' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TONER", "", "", "",
                                                       "http://tile.stamen.com/toner/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TONER RETINA' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TONER RETINA", "", "", "",
                                                       "http://tile.stamen.com/toner/{z}/{x}/{y}@2x.png", "", "22", "0"))
        if 'STAMEN TONER BACKGROUND' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TONER BACKGROUND", "", "", "",
                                                       "http://tile.stamen.com/toner-background/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TONER HYBRID' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TONER HYBRID", "", "", "",
                                                       "http://tile.stamen.com/toner-hybrid/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TONER LABELS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TONER LABELS", "", "", "",
                                                       "http://tile.stamen.com/toner-labels/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN TONER LITE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN TONER LITE", "", "", "",
                                                       "http://tile.stamen.com/toner-lite/{z}/{x}/{y}.png", "", "22", "0"))
        if 'STAMEN WATERCOLOR' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "STAMEN WATERCOLOR", "", "", "",
                                                       "http://tile.stamen.com/watercolor/{z}/{x}/{y}.jpg", "", "22", "0"))
        if 'BING MAP' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "BING MAP", "", "", "",
                                                       "http://ecn.dynamic.t0.tiles.virtualearth.net/comp/CompositionHandler/{q}?mkt=en-us&it=G,VE,BX,L,LA&shading=hill", "", "22", "0"))
        if 'BING SATELLITE' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "BING SATELLITE", "", "", "",
                                                       "http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g=0&dir=dir_n'", "", "22", "0"))
        if 'BING AERIAL' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "BING AERIAL", "", "", "",
                                                       "http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g=1", "", "22", "0"))
        if 'CARTODB DARK MATTER' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CARTODB DARK MATTER", "", "", "",
                                                       "http://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png", "", "22", "0"))
        if 'CARTODB DARK MATTER NO LABELS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CARTODB DARK MATTER NO LABELS", "", "", "",
                                                       "http://a.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png", "", "22", "0"))
        if 'CARTODB POSITRON' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CARTODB POSITRON", "", "", "",
                                                       "http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png", "", "22", "0"))
        if 'CARTODB POSITRON NO LABELS' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CARTODB POSITRON NO LABELS", "", "", "",
                                                       "http://a.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png", "", "22", "0"))
        if 'CARTODB VOYAGER' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CARTODB VOYAGER", "", "", "",
                                                       "https://a.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png", "", "22", "0"))
        if 'OPENRAILWAYMAP' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "OPENRAILWAYMAP", "", "", "",
                                                       "https://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png", "", "22", "0"))
        if 'SAFECAST' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "SAFECAST", "", "", "",
                                                       "https://s3.amazonaws.com/te512.safecast.org/{z}/{x}/{y}.png", "", "22", "0"))
        if 'CYCLOSM' in itemsToBeAdd:
            connectionList.append(connectionAtributtes(ogc, "CYCLOSM", "", "", "",
                                                       "https://a.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png", "", "22", "0"))

        self.setOwsConnection(sdi, connectionList)


    def removeOWSConnection(self, ogc, sdi, connection):
        if ogc == 'wms':
            base_path = f"connections/ows/items/wms/connections/items/{connection}"
            sdi.remove(base_path)
        elif ogc == 'wfs':
            base_path = f"connections/ows/items/wfs/connections/items/{connection}"
            sdi.remove(base_path)
        elif ogc == 'wcs':
            base_path = f"connections/ows/items/wcs/connections/items/{connection}"
            sdi.remove(base_path)
        elif ogc == 'xyz':
            base_path = f"connections/xyz/items/{connection}"
            sdi.remove(base_path)
        # ows_service = 'qgis/' + ogc
        # sdi.beginGroup(ows_service)
        # sdi.remove(connection)
        # sdi.endGroup()
        self.iface.reloadConnections()

    
    # Clead IDE_BA WFS Connections
    def cleanIDEBAwfsConnection(self, ogc, sdi):
        lista = ['IDE_BA_SANEAMENTO','IDE_BA_ADMINISTRACAO','IDE_BA_EDIFICACOES','IDE_BA_EDU_CULTURA','IDE_BA_ENERGIA','IDE_BA_ESTRUTURA','IDE_BA_HIDROGRAFIA',
                 'IDE_BA_LIMITES', 'IDE_BA_LOCALIDADES', 'IDE_BA_REFERENCIA', 'IDE_BA_RELEVO', 'IDE_BA_SAUDE', 'IDE_BA_TRANSPORTE', 'IDE_BA_VEGETACAO']
        for item in lista:
            self.removeOWSConnection(ogc, sdi, item)
            

    def removeAllConnectionsOWS(self, ogc, sdi, id):

        if id == 0:
            numberInstitutionsItems = self.dlg.listWidgetSelectedInstitutions.count()
            if (numberInstitutionsItems == 0):
                self.removeItemsWarning()
            for i in range(self.dlg.listWidgetSelectedInstitutions.count()):
                connection_name = self.dlg.listWidgetSelectedInstitutions.item(
                    i).text()
                if connection_name == 'IDE_BA' and ogc == 'wfs':
                    self.cleanIDEBAwfsConnection(ogc, sdi)

                self.removeOWSConnection(ogc, sdi, connection_name)
        else:
            numberBasemapsItems = self.dlg.listWidgetSelectedBasemaps.count()

            if (numberBasemapsItems == 0):
                self.removeItemsWarning()
            for i in range(self.dlg.listWidgetSelectedBasemaps.count()):
                connection_name = self.dlg.listWidgetSelectedBasemaps.item(
                    i).text()
                if connection_name == 'SENTINEL-2':
                    ogc = 'wms'
                self.removeOWSConnection(ogc, sdi, connection_name)

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

            class connectionAtributtes:
                def __init__(
                        self,
                        connectionType,
                        connectionName,
                        connectionAuthcfg,
                        connectionPassword,
                        connectionReferer,
                        connectionUrl,
                        connectionUsername,
                        connectionZmax,
                        connectionZmin):
                    self.connectionType = connectionType
                    self.connectionName = connectionName
                    self.connectionAuthcfg = connectionAuthcfg
                    self.connectionPassword = connectionPassword
                    self.connectionReferer = connectionReferer
                    self.connectionUrl = connectionUrl
                    self.connectionUsername = connectionUsername
                    self.connectionZmax = connectionZmax
                    self.connectionZmin = connectionZmin

            connectionList = []
            sdi = QSettings()
            owsConnectionType = {
                "xyz": 'xyz',
                "wms": 'wms',
                "wfs": 'wfs',
                "wcs": 'wcs',
            }
            wms = owsConnectionType.get('wms')
            wfs = owsConnectionType.get('wfs')
            wcs = owsConnectionType.get('wcs')
            xyz = owsConnectionType.get('xyz')

            institutionsId = 0
            # Obter lista atualizada de INDE_update.py
            institutions = InstLista
            
            outras = [
                'AESA_PB',
                'ANA_AQUACOOPE',
                'CELEPAR_PR',
                'CPRM_SACE',
                'DPC',
                'IDE_BA',
                #'INCRA',
                'INPE FOCOS DE CALOR',
                'INPE_CBERS',
                'PEM',
                'SFB_CAR'
            ]

            institutions += outras

            basemapsId = 1
            basemaps = ['SENTINEL-2',
                        'GOOGLE SATELLITE',
                        'GOOGLE TERRAIN',
                        'GOOGLE TERRAIN HYBRID',
                        'GOOGLE SATELLITE HYBRID',
                        'GOOGLE ROAD',
                        'GOOGLE MAPS',
                        'BING MAP',
                        'BING SATELLITE',
                        'BING AERIAL',
                        'OSM STANDARD',
                        'OSM OPENTOPOMAP',
                        'OSM HOT',
                        'OSM DEUTSCHLAND',
                        'OSM SWITZERLAND',
                        'OSM FRANCE',
                        'OSM BREZHONEG',
                        'OSM TRACKS',
                        'OSM HIKE & BIKE',
                        'OSM HILLSHADING',
                        'OSM GRAYSCALE',
                        'OSM NO LABELS',
                        'ESRI BOUNDARIES PLACES',
                        'ESRI GRAY DARK',
                        'ESRI GRAY LIGHT',
                        'ESRI NATIONAL GEOGRAPHIC',
                        'ESRI OCEAN',
                        'ESRI PHYSICAL',
                        'ESRI REFERENCE OVERLAY',
                        'ESRI SHADED RELIEF',
                        'ESRI SATELLITE',
                        'ESRI WORLD IMAGERY',
                        'ESRI STANDARD',
                        'ESRI TERRAIN'
                        ]
            # Adicionar basemaps

            self.populatelistWidget(institutions, institutionsId)
            self.populatelistWidget(basemaps, basemapsId)
            self.dlg.buttonAddAllItems.clicked.connect(lambda:
                                                       self.addAllItems(institutions, institutionsId))
            self.dlg.buttonAddAllBasemaps.clicked.connect(lambda:
                                                          self.addAllItems(basemaps, basemapsId))

            self.dlg.buttonAddSelectedItems.clicked.connect(lambda:
                                                            self.addSelectedItems(institutionsId))
            self.dlg.buttonAddSelectedBasemaps.clicked.connect(lambda:
                                                               self.addSelectedItems(basemapsId))
            self.dlg.listWidgetSelectedInstitutions.setSelectionMode(EXTENDED_SEL)
            self.dlg.listWidgetSelectedBasemaps.setSelectionMode(EXTENDED_SEL)
            self.dlg.buttonRemoveSelectedItems.clicked.connect(lambda:
                                                               self.removeSelectedItems(institutionsId))
            self.dlg.buttonRemoveSelectedBasemaps.clicked.connect(lambda:
                                                                  self.removeSelectedItems(basemapsId))
            self.dlg.buttonRemoveAllItems.clicked.connect(lambda:
                                                          self.removeAllItems(institutionsId))
            self.dlg.buttonRemoveAllBasemaps.clicked.connect(lambda:
                                                             self.removeAllItems(basemapsId))
            self.dlg.loadWmsLayers.clicked.connect(
                lambda: self.addWmsConnection(wms, sdi, connectionList, connectionAtributtes))
            self.dlg.loadWfsLayers.clicked.connect(
                lambda: self.addWfsConnection(wfs, sdi, connectionList, connectionAtributtes))
            self.dlg.loadWcsLayers.clicked.connect(
                lambda: self.addWcsConnection(wcs, sdi, connectionList, connectionAtributtes))
            self.dlg.loadXyzLayers.clicked.connect(
                lambda: self.addXyzConnection(xyz, sdi, connectionList, connectionAtributtes))
            self.dlg.wipeAllConnectionsWms.clicked.connect(lambda:
                                                           self.removeAllConnectionsOWS(wms, sdi, institutionsId))
            self.dlg.wipeAllConnectionsWfs.clicked.connect(lambda:
                                                           self.removeAllConnectionsOWS(wfs, sdi, institutionsId))
            self.dlg.wipeAllConnectionsWcs.clicked.connect(lambda:
                                                           self.removeAllConnectionsOWS(wcs, sdi, institutionsId))
            self.dlg.wipeAllConnectionsXyz.clicked.connect(lambda:
                                                           self.removeAllConnectionsOWS(xyz, sdi, basemapsId))

        # show the dialog
        self.dlg.geoonelogo.setCursor(QCursor(CURSOR_POINTING))
        self.dlg.geoonelogo.mousePressEvent = self.abrir_link_geoonelogo
        self.dlg.indeLogo.setCursor(QCursor(CURSOR_POINTING))
        self.dlg.indeLogo.mousePressEvent = self.abrir_link_inde
        self.dlg.show()
        
        # Run the dialog event loop
        try:
            result = self.dlg.exec()     # PyQt6
        except AttributeError:
            result = self.dlg.exec_()    # PyQt5
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
    
    def abrir_link_geoonelogo(self, event):
        QDesktopServices.openUrl(QUrl("https://geoone.com.br/conceitos-ide-geosservicos/"))
    
    def abrir_link_inde(self, event):
        QDesktopServices.openUrl(QUrl("https://www.inde.gov.br/CatalogoGeoservicos"))
