#coding=utf-8
#Copyright (C) 2015 IDAEA-CSIC
#
#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. This program is distributed in the hope that it will be useful, but 
#ITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
#PURPOSE. See the GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License along with this program; if not, write to 
#the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
'''
:copyright: Copyright (C) 2015 IDAEA-CSIC
:authors: V. Velasco Mansilla, L.M. de Vries, A. Nardi, R. Criollo, E. Vázquez Suñé
:contact: enric.vazquez@idaea.csic.es
:license: GPL General Public License, version 2 or any later version (http://opensource.org/licenses/GPL-2.0)
'''
from qgis.core import QgsDataSourceURI
from PyQt4.QtCore import QObject
from PyQt4.Qt import QSqlDatabase, QMessageBox
import os.path

class TABLES():
    '''
    Any references to actual database tables use the constants defined here. If a table name 
    changes, it only requires an update here. 
    '''
    SAVED_QUERY = "AK_SavedQueries"
    SAVED_QUERY_POINTS = "AK_SavedQueryPoints"
    SAVED_QUERY_SAMPLES = "AK_SavedQuerySamples"
    
    SAVED_QUERY_HYDRO = "AK_SavedQueriesHydro"
    SAVED_QUERY_POINTS_HYDRO= "AK_SavedQueryPointsHydro"
    SAVED_QUERY_SAMPLES_HYDRO = "AK_SavedQuerySamplesHydro"
    
    POINTS = "Points"
    
    CHEMSAMPLES = "HydrochemicalSamples"
    CHEMMEASUREMENTS = "HydrochemicalMeasurements"
    CHEMPARAMS = "ListHydrochemicalParametersCode"
    CHEMNORMPARAMS = "HydrochemicalNormativeParameters"
    
    HYDROSAMPLES = "HydrogeologicalPointsObservations"
    HYDROMEASUREMENTS = "HydrogeologicalPointsMeasurements"
    HYDROPARAMS = "ListHydrogeologicalParametersCode"
    
    CAMPAIGNS = "Campaigns"    
    WELLS = "Wells"
    NORMATIVES = "Normatives"
    PROJECTS = "Projects"
    PROCESSES = "Processes"
    RESPONSIBLES = "ResponsibleParties"
    CITATIONS = "Citations"
    L_UNITOFMEASUREMENTS = "ListUnitOfMeasurements"
    L_STATUSCODE = "ListStatusCode"
    L_ACTIVITYTYPE = "ListActivityType"
    L_CAMPAIGNTYPE = "ListCampaignType"
    L_GEOMSRCTYPE = "ListGeometrySourceType"
    REFSYSTEMS = "ReferenceSystems"
    L_POINTTYPE = "ListPointType"
    
    HYDROUNITSAPPEARANCE = "HydrogeologicalUnitsApparence"
    WELLS_HYDROUNIT = "WellsHydrogeologicalUnit"
    HYDROUNITS = "HydrogeologicalUnits"
    L_HYDROUNITTYPE = "ListHydroUnitType"
    L_RESULTSQUALITYCODE = "ListResultsQualityCode"
    L_RESULTSNATURECODE = "ListResultsNatureType"
    TIMEMETADATA = "TimeMetadata"
    L_FUNCTIONCODE = "ListFunctionCode"
    

class AKSettings (QObject):
    '''
    This class provides the functionality to open and close an AkvaGIS SQLite database. It also takes 
    care of the creation and deletion of related QGIS layers.  
    '''
    def __init__(self, parent=None):
        '''
        If a file called "userSettings.txt" exists in the same directory as this 
        source file, it is used to retrieve the most recently opened database.
        If not, it is created.
        The variable self.currentDB points to the database if it is opened, otherwise it is None.
        '''        
        super(AKSettings, self).__init__(parent)
        self.iface = parent
        self.currentDB = None
        self.dbGroup = None

        # FOR FREEWAT THIS SHOULD BE:
        
        self.userSettingsFileName = os.path.join(os.path.dirname(os.path.abspath(__file__)),"userSettings.txt") 
        if not os.path.isfile(self.userSettingsFileName):
            self.userSettingsFile = open(self.userSettingsFileName,'w')
            self.userSettingsFile.close()
        
        self.layersView = [TABLES.POINTS,
                          ("HydroChemistry",[TABLES.CAMPAIGNS,
                                             TABLES.CHEMSAMPLES,
                                             TABLES.CHEMMEASUREMENTS,
                                             TABLES.CHEMPARAMS,
                                             TABLES.L_CAMPAIGNTYPE]),
                           TABLES.HYDROUNITSAPPEARANCE,
                          ("HydroGeology",[TABLES.WELLS,
                                           TABLES.HYDROSAMPLES,
                                           TABLES.HYDROMEASUREMENTS,
                                           TABLES.HYDROPARAMS,
                                           TABLES.WELLS_HYDROUNIT,
                                           TABLES.HYDROUNITS,
                                           TABLES.L_HYDROUNITTYPE]),
                          TABLES.NORMATIVES,
                          TABLES.CHEMNORMPARAMS,
                          TABLES.L_UNITOFMEASUREMENTS,
                          TABLES.PROCESSES,
                          TABLES.RESPONSIBLES,
                          TABLES.CITATIONS,
                          TABLES.L_STATUSCODE,
                          TABLES.L_ACTIVITYTYPE,
                          TABLES.PROJECTS,
                          TABLES.L_GEOMSRCTYPE,
                          TABLES.REFSYSTEMS,
                          TABLES.L_POINTTYPE,
                          TABLES.L_RESULTSQUALITYCODE,
                          TABLES.L_RESULTSNATURECODE,
                          TABLES.TIMEMETADATA,
                          TABLES.L_FUNCTIONCODE
                          ]
        
        # TODO: m_availableTablesOrder can actually be created from self.layersView.
        self.m_availableTablesOrder = [TABLES.POINTS,
                                      TABLES.CAMPAIGNS,
                                      TABLES.CHEMSAMPLES,
                                      TABLES.CHEMMEASUREMENTS,
                                      TABLES.CHEMPARAMS,
                                      TABLES.WELLS,
                                      TABLES.L_UNITOFMEASUREMENTS,
                                      TABLES.CHEMNORMPARAMS,
                                      TABLES.PROCESSES,
                                      TABLES.RESPONSIBLES,
                                      TABLES.CITATIONS,
                                      TABLES.L_STATUSCODE,
                                      TABLES.L_ACTIVITYTYPE,
                                      TABLES.L_CAMPAIGNTYPE,
                                      TABLES.PROJECTS,
                                      TABLES.HYDROSAMPLES,
                                      TABLES.HYDROMEASUREMENTS,
                                      TABLES.HYDROPARAMS,
                                      TABLES.WELLS_HYDROUNIT,
                                      TABLES.HYDROUNITS,
                                      TABLES.L_HYDROUNITTYPE,
                                      TABLES.L_GEOMSRCTYPE,
                                      TABLES.REFSYSTEMS,
                                      TABLES.L_POINTTYPE,
                                      TABLES.HYDROUNITSAPPEARANCE,
                                      TABLES.L_RESULTSQUALITYCODE,
                                      TABLES.L_RESULTSNATURECODE,
                                      TABLES.TIMEMETADATA,
                                      TABLES.L_FUNCTIONCODE,
                                      TABLES.NORMATIVES
                                      ]
         
        # This structure contains references to all the open layers.
        # It also contains a description of the delegates to use in the QGIS table-edit view.
        # Note that if the order of fields in layers changes, these indexes need to be changed as well.
        self.m_availableTables = {TABLES.POINTS: {"geometryColumn" : "Geometry",
                                                  "relationalFields" : 
                                                             [{"fieldIndex" : 9,
                                                               "keyField" : "id",
                                                               "valueField" : "geometrySourceType",
                                                               "tableName" : TABLES.L_GEOMSRCTYPE},
                                                              {"fieldIndex" : 10,
                                                               "keyField" : "id",
                                                               "valueField" : "geometrySourceType",
                                                               "tableName" : TABLES.L_GEOMSRCTYPE},
                                                              {"fieldIndex" : 11,
                                                               "keyField" : "id",
                                                               "valueField" : "referenceSystem",
                                                               "tableName" : TABLES.REFSYSTEMS},
                                                              {"fieldIndex" : 12,
                                                               "keyField" : "id",
                                                               "valueField" : "referenceSystem",
                                                               "tableName" : TABLES.REFSYSTEMS},
                                                              {"fieldIndex" : 15,
                                                               "keyField" : "id",
                                                               "valueField" : "referenceSystem",
                                                               "tableName" : TABLES.REFSYSTEMS},
                                                              {"fieldIndex" : 16,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS},
                                                              {"fieldIndex" : 17,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS},
                                                              {"fieldIndex" : 18,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS},
                                                              {"fieldIndex" : 19,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS},
                                                              {"fieldIndex" : 22,
                                                               "keyField" : "id",
                                                               "valueField" : "pointType",
                                                               "tableName" : TABLES.L_POINTTYPE}
                                                            ]},
                                  TABLES.CHEMSAMPLES: {"relationalFields" : 
                                                             [{"fieldIndex" : 2,
                                                               "keyField" : "id",
                                                                "valueField" : "point",
                                                                 "tableName" : TABLES.POINTS,
                                                                 "layerName" : None,      # generated when creating layers
                                                                 "geometryColumn": None,  # generated when creating layers
                                                                 "layerObject" : None},   # generated when creating layers
                                                              {"fieldIndex" : 4,
                                                               "keyField" : "id",
                                                                "valueField" : "campaign",
                                                                 "tableName" : TABLES.CAMPAIGNS},
                                                              {"fieldIndex" : 8,
                                                               "keyField" : "id",
                                                                "valueField" : "nameEN",
                                                                 "tableName" : TABLES.L_UNITOFMEASUREMENTS},
                                                              {"fieldIndex" : 10,
                                                               "keyField" : "id",
                                                                "valueField" : "process",
                                                                 "tableName" : TABLES.PROCESSES},
                                                              {"fieldIndex" : 11,
                                                               "keyField" : "id",
                                                                "valueField" : "responsibleParty",
                                                                 "tableName" : TABLES.RESPONSIBLES}
                                                            ],
                                                        "dateTimeFields" : [{"fieldIndex" : 3}],
                                                        "nonEditableFields" : [{"fieldIndex" : 0}]
                                                        },
                                  TABLES.CHEMMEASUREMENTS: {"relationalFields" : 
                                                                     [{"fieldIndex" : 1,
                                                                       "keyField" : "id",
                                                                        "valueField" : "sample",
                                                                         "tableName" : TABLES.CHEMSAMPLES},
                                                                      {"fieldIndex" : 2,
                                                                       "keyField" : "id",
                                                                        "valueField" : "nameENWithUnit",
                                                                         "tableName" : TABLES.CHEMPARAMS},
                                                                      {"fieldIndex" : 6,
                                                                       "keyField" : "id",
                                                                       "valueField" : "responsibleParty",
                                                                       "tableName" : TABLES.RESPONSIBLES},
                                                                      {"fieldIndex" : 7,
                                                                       "keyField" : "id",
                                                                       "valueField" : "process",
                                                                       "tableName" : TABLES.PROCESSES},
                                                                      {"fieldIndex" : 8,
                                                                       "keyField" : "id",
                                                                       "valueField" : "citation",
                                                                       "tableName" : TABLES.CITATIONS}
                                                                    ],
                                                        "dateTimeFields" : [{"fieldIndex" : 3}],
                                                        "nonEditableFields" : [{"fieldIndex" : 0}]
                                                           },
                                  TABLES.CHEMPARAMS: {"relationalFields" : 
                                                             [{"fieldIndex" : 3,
                                                               "keyField" : "id",
                                                               "valueField" : "nameEN",
                                                               "tableName" : TABLES.L_UNITOFMEASUREMENTS}
                                                            ]
                                                           },
                                  TABLES.CHEMNORMPARAMS:{"relationalFields" : 
                                                             [{"fieldIndex" : 0,
                                                               "keyField" : "id",
                                                               "valueField" : "normative",
                                                               "tableName" : TABLES.NORMATIVES},
                                                              {"fieldIndex" : 1,
                                                               "keyField" : "id",
                                                               "valueField" : "nameENWithUnit",
                                                               "tableName" : TABLES.CHEMPARAMS}
                                                            ]
                                                           },
                                  TABLES.WELLS: {"relationalFields" : 
                                                        [{"fieldIndex" : 2,
                                                          "keyField" : "id",
                                                          "valueField" : "point",
                                                          "tableName" : TABLES.POINTS},
                                                         {"fieldIndex" : 10,
                                                          "keyField" : "id",
                                                          "valueField" : "responsibleParty",
                                                          "tableName" : TABLES.RESPONSIBLES},
                                                         {"fieldIndex" : 11,
                                                          "keyField" : "id",
                                                          "valueField" : "responsibleParty",
                                                          "tableName" : TABLES.RESPONSIBLES},
                                                         {"fieldIndex" : 12,
                                                          "keyField" : "id",
                                                          "valueField" : "nameEN",
                                                          "tableName" : TABLES.L_STATUSCODE},
                                                         {"fieldIndex" : 14,
                                                          "keyField" : "id",
                                                          "valueField" : "nameEN",
                                                          "tableName" : TABLES.L_STATUSCODE},
                                                         {"fieldIndex" : 22,
                                                          "keyField" : "id",
                                                          "valueField" : "pointType",
                                                          "tableName" : TABLES.L_POINTTYPE}
                                                        ],
                                                    "dateTimeFields" : [{"fieldIndex" : 3},
                                                                        {"fieldIndex" : 4},
                                                                        {"fieldIndex" : 9},
                                                                        {"fieldIndex" : 13}]
                                                    },
                                  TABLES.CAMPAIGNS: {"relationalFields" : 
                                                             [{"fieldIndex" : 2,
                                                               "keyField" : "id",
                                                               "valueField" : "campaignType",
                                                               "tableName" : TABLES.L_CAMPAIGNTYPE},
                                                              {"fieldIndex" : 3,
                                                               "keyField" : "id",
                                                               "valueField" : "project",
                                                               "tableName" : TABLES.PROJECTS},
                                                              {"fieldIndex" : 6,
                                                               "keyField" : "id",
                                                               "valueField" : "responsibleParty",
                                                               "tableName" : TABLES.RESPONSIBLES},
                                                              {"fieldIndex" : 7,
                                                               "keyField" : "id",
                                                               "valueField" : "responsibleParty",
                                                               "tableName" : TABLES.RESPONSIBLES},
                                                              {"fieldIndex" : 8,
                                                               "keyField" : "id",
                                                               "valueField" : "responsibleParty",
                                                               "tableName" : TABLES.RESPONSIBLES},
                                                              {"fieldIndex" : 9,
                                                               "keyField" : "id",
                                                               "valueField" : "responsibleParty",
                                                               "tableName" : TABLES.RESPONSIBLES}
                                                            ],
                                                    "dateTimeFields" : [{"fieldIndex" : 4},
                                                                        {"fieldIndex" : 5}]
                                                        },
                                  TABLES.HYDROUNITSAPPEARANCE: {"geometryColumn" : "Geometry",
                                                               "relationalFields" : 
                                                             [{"fieldIndex" : 2,
                                                               "keyField" : "id",
                                                               "valueField" : "hdyroUnit",
                                                               "tableName" : TABLES.HYDROUNITS},
                                                              {"fieldIndex" : 7,
                                                               "keyField" : "id",
                                                               "valueField" : "referenceSystem",
                                                               "tableName" : TABLES.REFSYSTEMS},
                                                              {"fieldIndex" : 8,
                                                               "keyField" : "id",
                                                               "valueField" : "referenceSystem",
                                                               "tableName" : TABLES.REFSYSTEMS},
                                                              {"fieldIndex" : 9,
                                                               "keyField" : "id",
                                                               "valueField" : "geometrySourceType",
                                                               "tableName" : TABLES.L_GEOMSRCTYPE}]},
                                  TABLES.L_UNITOFMEASUREMENTS: {},
                                  TABLES.PROCESSES: {"relationalFields" :
                                                            [{"fieldIndex" : 6,
                                                               "keyField" : "id",
                                                               "valueField" : "responsibleParty",
                                                               "tableName" : TABLES.RESPONSIBLES},
                                                              {"fieldIndex" : 7,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS}]},
                                  TABLES.RESPONSIBLES: {"relationalFields" :
                                                            [{"fieldIndex" : 18,
                                                               "keyField" : "id",
                                                               "valueField" : "functionCode",
                                                               "tableName" : TABLES.L_FUNCTIONCODE}]},
                                  TABLES.HYDROSAMPLES: {"relationalFields" : 
                                                             [{"fieldIndex" : 2,
                                                               "keyField" : "id",
                                                               "valueField" : "point",
                                                               "tableName" : TABLES.POINTS},
                                                              {"fieldIndex" : 3,
                                                               "keyField" : "id",
                                                               "valueField" : "nameENWithUnit",
                                                               "tableName" : TABLES.HYDROPARAMS},
                                                              {"fieldIndex" : 5,
                                                               "keyField" : "id",
                                                               "valueField" : "process",
                                                               "tableName" : TABLES.PROCESSES},
                                                              {"fieldIndex" : 7,
                                                               "keyField" : "id",
                                                               "valueField" : "timeMetadata",
                                                               "tableName" : TABLES.TIMEMETADATA},
                                                              {"fieldIndex" : 10,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS},
                                                              {"fieldIndex" : 11,
                                                               "keyField" : "id",
                                                               "valueField" : "responsibleParty",
                                                               "tableName" : TABLES.RESPONSIBLES},
                                                              {"fieldIndex" : 12,
                                                               "keyField" : "id",
                                                               "valueField" : "resultsQualityCode",
                                                               "tableName" : TABLES.L_RESULTSQUALITYCODE},
                                                              {"fieldIndex" : 13,
                                                               "keyField" : "id",
                                                               "valueField" : "resultsNatureType",
                                                               "tableName" : TABLES.L_RESULTSNATURECODE}],
                                                        "dateTimeFields" : [{"fieldIndex" : 6},
                                                                            {"fieldIndex" : 8},
                                                                            {"fieldIndex" : 9}]
                                                        },
                                  TABLES.CITATIONS: {"dateTimeFields" : [{"fieldIndex" : 9}]},
                                  TABLES.L_STATUSCODE: {},
                                  TABLES.L_ACTIVITYTYPE: {},
                                  TABLES.L_CAMPAIGNTYPE: {},
                                  TABLES.PROJECTS: {},
                                  TABLES.HYDROMEASUREMENTS: {"relationalFields" :
                                                            [{"fieldIndex" : 1,
                                                               "keyField" : "id",
                                                               "valueField" : "hydroPointObservation",
                                                               "tableName" : TABLES.HYDROSAMPLES}],
                                                             "dateTimeFields" : [{"fieldIndex" : 2}],
                                                             "nonEditableFields" : [{"fieldIndex" : 0}]},
                                  TABLES.HYDROPARAMS: {},
                                  TABLES.WELLS_HYDROUNIT: {"relationalFields" :
                                                            [{"fieldIndex" : 3,
                                                               "keyField" : "id",
                                                               "valueField" : "nameEN",
                                                               "tableName" : TABLES.HYDROUNITS}]},
                                  TABLES.HYDROUNITS: {"relationalFields" :
                                                            [{"fieldIndex" : 6,
                                                               "keyField" : "id",
                                                               "valueField" : "hydroUnitType",
                                                               "tableName" : TABLES.L_HYDROUNITTYPE},
                                                             {"fieldIndex" : 7,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS}]},
                                  TABLES.L_HYDROUNITTYPE: {},
                                  TABLES.L_GEOMSRCTYPE: {},
                                  TABLES.REFSYSTEMS: {},
                                  TABLES.L_POINTTYPE: {},
                                  TABLES.L_RESULTSQUALITYCODE: {},
                                  TABLES.L_RESULTSNATURECODE: {},
                                  TABLES.TIMEMETADATA: {},
                                  TABLES.L_FUNCTIONCODE: {},
                                  TABLES.NORMATIVES: {"relationalFields" :
                                                            [{"fieldIndex" : 2,
                                                               "keyField" : "id",
                                                               "valueField" : "responsibleParty",
                                                               "tableName" : TABLES.RESPONSIBLES},
                                                              {"fieldIndex" : 6,
                                                               "keyField" : "id",
                                                               "valueField" : "citation",
                                                               "tableName" : TABLES.CITATIONS}],
                                                      "dateTimeFields" : [{"fieldIndex" : 5}]}
                                  }
    
    def verifyAkvaGISDB(self):
        '''Verify if the opened SQLite file is really a AkvaGIS database. Returns True or False.'''
        tablesToCheck = [TABLES.SAVED_QUERY,
                         TABLES.SAVED_QUERY_POINTS,
                         TABLES.SAVED_QUERY_SAMPLES,
                         TABLES.SAVED_QUERY_HYDRO,
                         TABLES.SAVED_QUERY_POINTS_HYDRO,
                         TABLES.SAVED_QUERY_SAMPLES_HYDRO,
                         TABLES.POINTS,
                         TABLES.CHEMSAMPLES,
                         TABLES.CHEMMEASUREMENTS,
                         TABLES.CAMPAIGNS,
                         TABLES.HYDROSAMPLES,
                         TABLES.HYDROMEASUREMENTS]
        allTables = self.currentDB.tables()
        containsAllTables = True
        for curTable in tablesToCheck:
            if curTable not in allTables:
                containsAllTables = False
        return containsAllTables 
    
    def openCurrentDB(self, dbFilePath):
        '''Opens a database and assign it to self.currentDB'''
        isError = False
        if not os.path.isfile(dbFilePath):
            QMessageBox.warning(self.iface.mainWindow(),
                        "Warning",
                        "File " + dbFilePath + " not found")
            isError = True
        try:    
            self.currentDB = self.openSqliteDatabaseFile(dbFilePath)
        except:
            QMessageBox.warning(self.iface.mainWindow(),
                        "Warning",
                        "Not possible to connect to " + dbFilePath)
            isError = True
            
        return isError
    
    def setUserSettings(self, settingName, settingValue):
        '''Save settings, like the most recently opened database in a text file.'''
        self.userSettingsFile = open(self.userSettingsFileName,"r")
        lines = self.userSettingsFile.readlines()
        self.userSettingsFile.close()
        self.userSettingsFile = open(self.userSettingsFileName,"w")
        keyWord = settingName + "=" 
        for line in lines:
            if not keyWord in line:
                self.userSettingsFile.write(line)            
        newLine = keyWord + settingValue +"\n"
        self.userSettingsFile.write(newLine)
        self.userSettingsFile.close()
        
    def getUserSettings(self, settingName):
        '''Retrieve settings, like the most recently opened database from a text file.'''
        settingValue = ""
        self.userSettingsFile = open(self.userSettingsFileName,"r")
        for line in self.userSettingsFile:
            strippedLine = line.strip()
            lineParts = strippedLine.split("=")
            if len(lineParts) > 1:
                settingValue = lineParts[1]
                break
        return settingValue        

    def getCurrentDB(self):
        return self.currentDB
    
    def closeCurrentDB(self):
        if(self.currentDB != None):
            self.currentDB.close()
            self.currentDB = None
    
    def openSqliteDatabaseFile(self, fileName):
        newlyAddedDB = QSqlDatabase.addDatabase("QSQLITE", fileName)
        newlyAddedDB.setDatabaseName(fileName)
        db = QSqlDatabase.database(connectionName=fileName, open=True)
        if(not db.isValid()):
            newlyAddedDB = None
        else:
            print("Opened AkvaGIS database: " + fileName)
        return newlyAddedDB
    
    def getLayerDBPath(self, layer):
        '''Returns path to database directly from the provided layer.'''
        dbFileName = ""
        if(layer != None):
            provider = layer.dataProvider()
            providerURISource = provider.dataSourceUri()
            uri = QgsDataSourceURI(providerURISource)
            dbFileName = uri.database()
        return dbFileName
    
    def getActiveLayerDBPath(self):
        activeLayer = self.iface.activeLayer()
        dbFileName = self.getLayerDBPath(activeLayer)
        return dbFileName

    def getIconPath(self, filename):
        return os.path.join(os.path.dirname(__file__), 'icons', filename)
