# -*- coding:utf-8 -*-
"""
/***************************************************************************
 db_setting.py

 DbSetting class allow to set database storage

        begin                : 2021-03-15
        git sha              : $Format:%H$
        copyright            : (C) 2021 by Jean-Marie Arsac
        email                : jmarsac@azimut.fr
        
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.core import (
    QgsAbstractDatabaseProviderConnection,
    QgsProviderConnectionException,
    QgsProviderRegistry,
)


class DbSetting:
    def __init__(self, provider_name):
        """Constructor"""
        self.__connections = (
            QgsProviderRegistry.instance().providerMetadata(provider_name).connections()
        )
        self.__connection = None

    def load_connections_in_combobox(self, cbox):
        cbox.clear()
        for k in self.__connections.keys():
            cbox.addItem(k)

        cbox.setCurrentIndex(0)

    def load_schemas_in_combobox(self, cbox, schema_name=None):
        cbox.clear()
        try:
            for schema in self.__connection.schemas():
                cbox.addItem(schema)

            if schema_name:
                cbox.setCurrentText(schema_name)
            else:
                cbox.setCurrentIndex(0)
        except:
            pass

    def set_connection(self, connection_name):
        self.__connection = self.__connections[connection_name]

    def schemas(self):
        if self.__connection:
            return self.__connection.schemas()
        return []

    def connection(self):
        return self.__connection

    def create_schema(self, schema_name):
        if self.__connection:
            self.__connection.createSchema(schema_name)

    def execute_sql(self, sql_statement):
        if self.__connection:
            return self.__connection.executeSql(sql_statement.strip())
        return None

    def table_uri(self, schema, tablename):
        if self.__connection:
            return self.__connection.tableUri(schema, tablename)
        return None

    def table_exists(self, schema, tablename):

        if self.__connection:
            return self.__connection.tableExists(schema, tablename)
        return None

    def update_search_path(self, schema):
        query = "SELECT current_setting('search_path')"
        results = self.execute_sql(query)
        if results:
            if schema not in results[0][0]:
                query = "SET search_path TO " + schema + ", " + results[0][0]
                self.execute_sql(query)
