import logging
import os

from collections import namedtuple
from enum import Enum
from functools import partial
from pathlib import Path
from xml.dom.minidom import parseString
from qgis.gui import *
from qgis.core import (
    NULL,
    QgsApplication,
    QgsDataSourceUri,
    QgsProject,
    QgsProviderConnectionException,
    QgsProviderRegistry,
    QgsRasterLayer,
    QgsSettings,
    QgsVectorLayer,
    QgsGeometry,
    QgsWkbTypes,
)
from PyQt5 import QtGui
from qgis.PyQt.QtCore import QLocale, QUrl, QDateTime
from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtPrintSupport import QPrinter
from qgis.PyQt.QtWebKitWidgets import QWebPage
from qgis.PyQt.QtWidgets import (
    QDialog,
    QAction,
    QDockWidget,
    QFileDialog,
    QInputDialog,
    QMenu,
    QToolButton,
    QTableWidget, 
    QTableWidgetItem,
)
from qgis.utils import iface

from .tools.resources import (
    load_ui,
    resources_path,
    login_base,
    send_issues,
)
from .issues import CenRa_Issues

EDITOR_CLASS = load_ui('CenRa_Metabase_editorwidget_base.ui')
LOGGER = logging.getLogger('CenRa_Metabase')

class Metabase_Editor(QDialog, EDITOR_CLASS):

    def __init__(self, parent=None):
        _ = parent
        super().__init__()
        self.setupUi(self)
        self.settings = QgsSettings()
        self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png')))
        self.import_xml.setAutoRaise(True)
        self.import_xml.setText('')
        self.import_xml.setIcon(QIcon(QgsApplication.iconPath('mActionAddHtml.svg')))
        self.import_xml.clicked.connect(self.py_import_xml)
        self.issues_app.setAutoRaise(True)
        self.issues_app.setText('')
        self.issues_app.setIcon(QIcon(QgsApplication.iconPath('mIconInfo.svg')))
        self.auto_adding.setIcon(QtGui.QIcon(resources_path('icons','auto_add.png')))
        self.auto_adding.hide()
        if os.getlogin() == 'tlaveille' or 'lpoulin' or 'rclement':
            self.auto_adding.show()

        self.auto_adding.clicked.connect(self.auto_run)
        self.issues_app.clicked.connect(self.issues_open)
        self.categories_select_view.itemDoubleClicked.connect(self.add_categories_view)
        self.categories_view.itemDoubleClicked.connect(self.deleter_categories_view)
        self.themes_select_view.itemDoubleClicked.connect(self.add_themes_view)
        self.themes_view.itemDoubleClicked.connect(self.deleter_themes_view)

        self.annuler_button.clicked.connect(self.close)
        self.ok_button.clicked.connect(self.add_metadata)

        self.add_lien_button.clicked.connect(self.add_lien)
        self.add_contact_button.clicked.connect(self.add_contact)
        self.delete_lien_button.clicked.connect(self.delete_lien)
        self.delete_contact_button.clicked.connect(self.delete_contact)

    def auto_run(self):
        self.role_box.setCurrentIndex(1)
        self.nom_line.setText('LAVEILLE')
        self.organisation_box.setCurrentIndex(1)
        self.email_line.setText('tom.laveille@cen-rhonealpes.fr')
        self.telephone_line.setText('0451260811')
        self.add_contact()

        self.type_box.setCurrentIndex(16)
        self.url_line.setText('www.cen-rhonealpes.fr')
        self.mime_box.setCurrentIndex(16)
        self.format_box.setCurrentIndex(0)
        self.taille_line.setText('45')
        self.add_lien()
    def add_metadata(self):
        table_name = layer.dataProvider().uri().table()
        schema_name = layer.dataProvider().uri().schema()
        text_titre = self.titre_line.text()
        text_description = self.description_text.toPlainText()
        text_mots_cles = self.mots_cles_text.toPlainText()
        text_date_maj = str(self.date_maj_date.date().toPyDate())
        text_langue = self.langue_box.currentText()

        row_count_categories = self.categories_view.rowCount()
        row_count_themes = self.themes_view.rowCount()
        row = 1
        array_categories = '{'
        while row_count_categories >= row:
            if row_count_categories != row:
                array_categories += (self.categories_view.item(row-1,0).text())+','
            else:
                array_categories += (self.categories_view.item(row-1,0).text())
            row = row+1
        array_categories += '}'
        row = 1
        array_themes = '{'
        while row_count_themes >= row:
            if row_count_themes != row:
                array_themes += (self.themes_view.item(row-1,0).text())+','
            else:
                array_themes += (self.themes_view.item(row-1,0).text())
            row = row+1
        array_themes += '}'

        text_date_creation = str(self.date_creation_date.date().toPyDate())
        text_date_modification = str(self.date_modification_date.date().toPyDate())
        text_encode = self.encodage_box.currentText()
        text_extend = self.extend_plaintext.toPlainText()
        int_nbr_entites = (self.nbr_layers.toPlainText())
        text_geomtype = self.typegeom_plaintext.toPlainText()
        text_crsname = self.crsname_plaintext.toPlainText()
        text_crscode = self.crscode_plaintext.toPlainText()
        text_niveau = self.niveau_plain.toPlainText()

        text_echelle_min = self.echelle_min_plain.toPlainText()
        text_echelle_max = self.echelle_max_plain.toPlainText()
        if text_echelle_min == '':
            text_echelle_min = 'NULL'
        if text_echelle_max == '':
            text_echelle_max = 'NULL'

        text_date_publication = str(self.date_publication_date.date().toPyDate())

        text_frequence = self.frequence_box.currentText()
        text_restriction = self.restriction_box.currentText()
        text_licence = self.licence_box.currentText()
        text_licence_attrib = self.licence_attrib_box.currentText()

        '''
        row_count_link = self.table_lien.rowCount()
        row = 1
        array_link = ''
        while row_count_link >= row:
            if row_count_link != row:
                array_link += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_lien.item(row-1,1).text()) +"','"+ (self.table_lien.item(row-1,2).text()) +"','"+ (self.table_lien.item(row-1,3).text()) +"','"+ (self.table_lien.item(row-1,4).text()) +"','"+ (self.table_lien.item(row-1,5).text()) +"')"+','
            else:
                array_link += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_lien.item(row-1,1).text()) +"','"+ (self.table_lien.item(row-1,2).text()) +"','"+ (self.table_lien.item(row-1,3).text()) +"','"+ (self.table_lien.item(row-1,4).text()) +"','"+ (self.table_lien.item(row-1,5).text()) +"')"
            row = row+1

        row_count_contact = self.table_contact.rowCount()
        row = 1
        array_contact = ''
        while row_count_contact >= row:
            if row_count_contact != row:
                array_contact += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_contact.item(row-1,1).text()) +"','"+ (self.table_contact.item(row-1,2).text()) +"','"+ (self.table_contact.item(row-1,3).text()) +"','"+ (self.table_contact.item(row-1,4).text()) +"','"+ (self.table_contact.item(row-1,5).text()) +"')"+','
            else:
                array_contact += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_contact.item(row-1,1).text()) +"','"+ (self.table_contact.item(row-1,2).text()) +"','"+ (self.table_contact.item(row-1,3).text()) +"','"+ (self.table_contact.item(row-1,4).text()) +"','"+ (self.table_contact.item(row-1,5).text()) +"')"
            row = row+1
        '''

        exist=self.status_metadata(layer)
        cur_con=login_base(take=True)
        cur=cur_con[0]
        con=cur_con[1]
        list_champs_sql = ''
        values_sql_add = ''
        if exist:
            SQL_uid = """SELECT uid from metadata.dataset where table_name like '"""+table_name+"""' and schema_name like '"""+schema_name+"""';"""
            cur.execute(SQL_uid)
            text_uid = (cur.fetchall())[0][0]

            SQL_delete = """DELETE from metadata.dataset where table_name like '"""+table_name+"""' and schema_name like '"""+schema_name+"""';"""
            cur.execute(SQL_delete)
            values_sql_add += "'"+text_uid+"',"

            list_champs_sql+='uid,'
            global uid_delete_list_link,uid_delete_list_contact
            if len(uid_delete_list_link) >= 35:
                SQL_delete_link = """DELETE FROM metadata.dataurl WHERE uid IN ("""+ uid_delete_list_link[:-1] +""");"""
                cur.execute(SQL_delete_link)
                uid_delete_list_link = ''
            if len(uid_delete_list_contact) >= 35:
                SQL_delete_contact = """DELETE FROM metadata.datacontact WHERE uid IN ("""+ uid_delete_list_contact[:-1] +""");"""
                cur.execute(SQL_delete_contact)
                uid_delete_list_contact=''

        list_champs_sql += 'table_name,schema_name,title,abstract,keywords,data_last_update,langue,categories,themes,creation_date,update_date,encode,geom,spatial_extent,feature_count,geometry_type,projection_name,projection_authid,spatial_level,minimum_optimal_scale,maximum_optimal_scale,publication_date,publication_frequency,confidentiality,license,license_attribution'
        values_sql_add += "'"+table_name+"','"+schema_name+"','"+text_titre+"','"+text_description+"','"+text_mots_cles+"','"+text_date_maj+"','"+text_langue+"','"+array_categories+"','"+array_themes+"','"+text_date_creation+"','"+text_date_modification+"','"+text_encode+"','"+text_extend+"','"+text_extend+"','"+int_nbr_entites+"','"+text_geomtype+"','"+text_crsname+"','"+text_crscode+"','"+text_niveau+"',"+text_echelle_min+","+text_echelle_max+",'"+text_date_publication+"','"+text_frequence+"','"+text_restriction+"','"+text_licence+"','"+text_licence_attrib+"'"

        SQL_add = """INSERT INTO metadata.dataset ("""+list_champs_sql+""") VALUES ("""+values_sql_add+""");"""

        cur.execute(SQL_add)

        global array_link,array_contact
        if len(array_link) >= 25:
            array_link=array_link[:-1]
            SQL_add_link = """INSERT INTO metadata.dataurl (table_name,schema_name,type,url,mime,format,taille) VALUES """+array_link+""";"""
            cur.execute(SQL_add_link)
            array_link = ''

        if len(array_contact) >= 25:
            array_contact=array_contact[0:-1]
            SQL_add_contact = """INSERT INTO metadata.datacontact (table_name,schema_name,role,nom,organisation,email,telephone) VALUES """+array_contact+""";"""
            cur.execute(SQL_add_contact)
            array_contact = ''

        con.commit()
        cur.close()
        self.close()

        iface.layerTreeView().setCurrentLayer(None)
        iface.layerTreeView().setCurrentLayer(layer)

    def raise_(self):
        self.activateWindow()
        global layer
        layer = iface.activeLayer()
        global uid_delete_list_link,uid_delete_list_contact,array_link,array_contact
        uid_delete_list_link=''
        uid_delete_list_contact=''
        array_link = ''
        array_contact = ''

        is_ok=self.is_in_psql(layer)
        if is_ok:
            exist=self.status_metadata(layer)
            if exist:
                self.reload_data(layer)
            else:
                self.new_data(layer)
        else:
            self.close()
            iface.messageBar().pushMessage("Information :", "Cette couche n'est pas stockée dans PostgreSQL", level=Qgis.Warning, duration=30)

    def is_in_psql(self,layer):
        try:
            uri = layer.dataProvider().uri()
        except:
            uri=''
            return False
        if uri != '':
            if not uri.table():
                return False
            else:
                return True

    def status_metadata(self,layer):
        uri = layer.dataProvider().uri()
        table = uri.table()
        schema = uri.schema()

        cur=login_base()
        count_sql = """ SELECT count(uid) FROM metadata.dataset WHERE table_name LIKE '"""+table+"""' AND schema_name LIKE '"""+schema+"""';"""

        cur.execute(count_sql)
        data_count = (cur.fetchall())[0][0]
        if data_count == 1:
            return True
        else:
            return False
        cur.close()

    def new_data(self,layer):
        #print(layer.name(),'is new data')
        reloader=False
        self.interface_view(layer,reloader)

    def reload_data(self,layer):
        #print(layer.name(),'reload data')
        reloader=True
        self.interface_view(layer,reloader)

    def interface_view(self,layer,reloader):

        self.description_text.setText(None)
        self.mots_cles_text.setText(None)
        self.uuid_ligne.setText(None)
        self.niveau_plain.setPlainText(None)
        self.echelle_min_plain.setPlainText(None)
        self.echelle_max_plain.setPlainText(None)
        self.url_line.setText(None)
        self.taille_line.setText(None)
        self.nom_line.setText(None)
        self.email_line.setText(None)
        self.telephone_line.setText(None)
        self.encodage_box.clear()
        self.frequence_box.clear()
        self.licence_box.clear()
        self.licence_attrib_box.clear()
        self.restriction_box.clear()

        all_list=self.fletch_ref()

        categories_list=all_list[0]
        themes_list=all_list[1]
        langue_list=all_list[2]
        encodage_list=all_list[3]
        frequency_list=all_list[4]
        confidentiality_list=all_list[5]
        license_list=all_list[6]
        type_list=all_list[7]
        mime_list=all_list[8]
        format_list=all_list[9]
        role_list=all_list[10]
        organisation_list=all_list[11]


        #langue_box
        self.langue_box.clear()
        self.langue_box.addItem('')
        #self.langue_box.addItem('Fr')
        #self.langue_box.addItem('En')
        for langue_list_data in langue_list:
            self.langue_box.addItem(langue_list_data[0])

        for encodage_list_data in encodage_list:
            self.encodage_box.addItem(encodage_list_data[0])

        self.table_ligne.setText(layer.dataProvider().uri().table())
        self.schema_ligne.setText(layer.dataProvider().uri().schema())

        #categories_select_view
        self.categories_select_view.setColumnCount(1)
        self.categories_select_view.setColumnWidth(0, 230)
        self.categories_select_view.setHorizontalHeaderLabels(['List des categories'])
        #categories_view
        self.categories_view.setRowCount(0)
        self.categories_view.setColumnCount(1)
        self.categories_view.setColumnWidth(0, 230)
        self.categories_view.setHorizontalHeaderLabels(['Categories'])

        #themes_select_view
        self.themes_select_view.setColumnCount(1)
        self.themes_select_view.setColumnWidth(0, 230)
        self.themes_select_view.setHorizontalHeaderLabels(['List des thèmes'])
        #themes_view
        self.themes_view.setRowCount(0)
        self.themes_view.setColumnCount(1)
        self.themes_view.setColumnWidth(0, 230)
        self.themes_view.setHorizontalHeaderLabels(['Thèmes'])

        #lien_view
        self.table_lien.setRowCount(0)
        self.table_lien.setColumnCount(6)
        self.table_lien.setColumnWidth(0, 0)
        self.table_lien.setHorizontalHeaderLabels(['','Type','URL','MIME','Format','Taille'])

        #contact_view
        self.table_contact.setRowCount(0)
        self.table_contact.setColumnCount(6)
        self.table_contact.setColumnWidth(0, 0)
        self.table_contact.setHorizontalHeaderLabels(['','Rôle','Nom','Organisation','Email','Telephone'])

        #print(self.date_maj_date.date().toPyDate())
        vector_extend = layer.extent()
        polygone_extend = QgsGeometry.fromRect(vector_extend).asWkt()
        self.extend_plaintext.setPlainText(str(polygone_extend))

        qgstype = str(layer.type())[10:]

        if qgstype != 'Raster' :
            count_layers = str(layer.featureCount())
            geomtype = QgsWkbTypes.displayString(layer.wkbType())
        elif qgstype == 'Raster':
            count_layers = str(layer.dataProvider().bandCount())
            geomtype = qgstype

        self.nbr_layers.setPlainText(count_layers)
        self.typegeom_plaintext.setPlainText(geomtype)
        crs_name = str(layer.crs().description())
        self.crsname_plaintext.setPlainText(crs_name)
        crs_code = str(layer.crs().authid())
        self.crscode_plaintext.setPlainText(crs_code)


        self.frequence_box.addItem('')
        self.restriction_box.addItem('')
        self.licence_box.addItem('')
        self.licence_attrib_box.addItem('')
        for frequency_list_data in frequency_list:
            self.frequence_box.addItem(frequency_list_data[0])
        for confidentiality_list_data in confidentiality_list:
            self.restriction_box.addItem(confidentiality_list_data[0])
        for license_list_data in license_list:
            self.licence_box.addItem(license_list_data[0])

        self.type_box.clear()
        self.mime_box.clear()
        self.format_box.clear()
        self.role_box.clear()
        self.organisation_box.clear()

        self.type_box.addItem('')
        self.mime_box.addItem('')
        self.format_box.addItem('')
        self.role_box.addItem('')
        self.organisation_box.addItem('')

        for type_list_data in type_list:
            self.type_box.addItem(type_list_data[0])
        for mime_list_data in mime_list:
            self.mime_box.addItem(mime_list_data[0])
        for format_list_data in format_list:
            self.format_box.addItem(format_list_data[0])
        for role_list_data in role_list:
            self.role_box.addItem(role_list_data[0])
        for organisation_list_data in organisation_list:
            self.organisation_box.addItem(organisation_list_data[0])

        if reloader:
            sql_dataload=self.sql_info(layer.dataProvider().uri())
            sql_contactlink=self.sql_infoother(layer.dataProvider().uri())
            sql_datalink=sql_contactlink[0]
            sql_datacontact=sql_contactlink[1]

            #print(sql_dataload)
            self.titre_line.setText(sql_dataload[4])
            self.date_maj_date.setDateTime(sql_dataload[23])
            self.date_publication_date.setDateTime(sql_dataload[11])
            self.description_text.setText(sql_dataload[5])
            self.mots_cles_text.setText(sql_dataload[7])
            array_langue_box = [self.langue_box.itemText(i) for i in range(self.langue_box.count())]
            self.langue_box.setCurrentIndex(array_langue_box.index(sql_dataload[26]))
            self.uuid_ligne.setText(sql_dataload[1])

            self.categories_view.setRowCount(len(sql_dataload[6]))
            i=0
            for categorie_data in sql_dataload[6]:
                self.categories_view.setItem(i,0,QTableWidgetItem(categorie_data))
                i=i+1
            self.themes_view.setRowCount(len(sql_dataload[24]))
            i=0
            for themes_data in sql_dataload[24]:
                self.themes_view.setItem(i,0,QTableWidgetItem(themes_data))
                i=i+1

            self.categories_select_view.setRowCount(len(categories_list)-len(sql_dataload[6]))
            self.themes_select_view.setRowCount(len(themes_list)-len(sql_dataload[24]))
            i=0
            for categorie_select_data in categories_list:
                try:
                    in_index = sql_dataload[6].index(categorie_select_data[0])
                    in_index=False
                except:
                    in_index=True
                if in_index:
                    self.categories_select_view.setItem(i,0,QTableWidgetItem(categorie_select_data[0]))
                    i=i+1
            i=0
            for themes_select_data in themes_list:
                try:
                    in_index = sql_dataload[24].index(themes_select_data[0])
                    in_index=False
                except:
                    in_index=True
                if in_index:
                    self.themes_select_view.setItem(i,0,QTableWidgetItem(themes_select_data[0]))
                    i=i+1

            array_encodage_box = [self.encodage_box.itemText(i) for i in range(self.encodage_box.count())]
            self.encodage_box.setCurrentIndex(array_encodage_box.index(sql_dataload[27]))

            self.niveau_plain.setPlainText(sql_dataload[8])

            if str(sql_dataload[9]) == 'None':
                value_echelle_min = ''
            else:
                value_echelle_min = str(sql_dataload[9])

            if str(sql_dataload[10]) == 'None':
                value_echelle_max = ''
            else:
                value_echelle_max = str(sql_dataload[10])

            self.echelle_min_plain.setPlainText(value_echelle_min)
            self.echelle_max_plain.setPlainText(value_echelle_max)

            array_frequence_box = [self.frequence_box.itemText(i) for i in range(self.frequence_box.count())]
            self.frequence_box.setCurrentIndex(array_frequence_box.index(sql_dataload[12]))
            array_licence_box = [self.licence_box.itemText(i) for i in range(self.licence_box.count())]
            self.licence_box.setCurrentIndex(array_licence_box.index(sql_dataload[13]))
            array_confidentiality_box = [self.restriction_box.itemText(i) for i in range(self.restriction_box.count())]
            self.restriction_box.setCurrentIndex(array_confidentiality_box.index(sql_dataload[14]))
            array_licence_attrib_box = [self.licence_attrib_box.itemText(i) for i in range(self.licence_attrib_box.count())]
            self.licence_attrib_box.setCurrentIndex(array_licence_attrib_box.index(sql_dataload[25]))

            c=0
            #self.table_lien.setRowCount(len(sql_datalink))
            for lien_data in sql_datalink:
                self.table_lien.insertRow(c)
                self.table_lien.setItem(c,0,QTableWidgetItem(lien_data[1]))
                self.table_lien.setItem(c,1,QTableWidgetItem(lien_data[4]))
                self.table_lien.setItem(c,2,QTableWidgetItem(lien_data[5]))
                self.table_lien.setItem(c,3,QTableWidgetItem(lien_data[6]))
                self.table_lien.setItem(c,4,QTableWidgetItem(lien_data[7]))
                self.table_lien.setItem(c,5,QTableWidgetItem(lien_data[8]))
                c=c+1
            c=0
            #self.table_contact.setRowCount(len(sql_datacontact))
            for contact_data in sql_datacontact:
                self.table_contact.insertRow(c)
                self.table_contact.setItem(c,0,QTableWidgetItem(contact_data[1]))
                self.table_contact.setItem(c,1,QTableWidgetItem(contact_data[4]))
                self.table_contact.setItem(c,2,QTableWidgetItem(contact_data[5]))
                self.table_contact.setItem(c,3,QTableWidgetItem(contact_data[6]))
                self.table_contact.setItem(c,4,QTableWidgetItem(contact_data[7]))
                self.table_contact.setItem(c,5,QTableWidgetItem(contact_data[8]))
                c=c+1

        else:

            #titre_line
            self.titre_line.setText(layer.name())
            self.langue_box.setCurrentIndex(1)
            #date_maj_date
            now = QtCore.QDateTime.currentDateTime()
            self.date_maj_date.setDateTime(now)
            self.date_creation_date.setDateTime(now)
            self.date_modification_date.setDateTime(now)
            self.date_publication_date.setDateTime(now)
            self.categories_select_view.setRowCount(len(categories_list))
            self.themes_select_view.setRowCount(len(themes_list))
            i=0
            for categorie_select_data in categories_list:
                self.categories_select_view.setItem(i,0,QTableWidgetItem(categorie_select_data[0]))
                i=i+1
            i=0
            for themes_select_data in themes_list:
                self.themes_select_view.setItem(i,0,QTableWidgetItem(themes_select_data[0]))
                i=i+1

        #print(self.langue_box.currentText())

    def sql_info(self,uri):
        cur=login_base()
        table = uri.table()
        schema = uri.schema()
        #[s for s in iface.activeLayer().source().split(" ") if "dbname" in s][0].split("'")[1]
        sql_find = """SELECT *,right(left(st_astext(geom,2),-2),-9) FROM metadata.dataset
            WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
        cur.execute(sql_find)
        data_general = cur.fetchall()
        cur.close()
        return data_general[0]

    def sql_infoother(self,uri):
        cur=login_base()
        table = uri.table()
        schema = uri.schema()

        sql_findlink = """SELECT * FROM metadata.dataurl
            WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
        cur.execute(sql_findlink)
        data_link = cur.fetchall()

        sql_findcontact = """SELECT * FROM metadata.datacontact
            WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
        cur.execute(sql_findcontact)
        data_contact = cur.fetchall()

        cur.close()
        return data_link,data_contact

    def add_categories_view(self):
        values_add_categories = self.categories_select_view.selectedItems()[0].text()
        self.categories_select_view.removeRow(self.categories_select_view.currentRow())
        self.categories_view.insertRow(0)
        self.categories_view.setItem(0,0,QTableWidgetItem(values_add_categories))
    def deleter_categories_view(self):
        values_deleter_categories = self.categories_view.selectedItems()[0].text()
        self.categories_view.removeRow(self.categories_view.currentRow())
        self.categories_select_view.insertRow(0)
        self.categories_select_view.setItem(0,0,QTableWidgetItem(values_deleter_categories))

    def add_themes_view(self):
        values_add_themes = self.themes_select_view.selectedItems()[0].text()
        self.themes_select_view.removeRow(self.themes_select_view.currentRow())
        self.themes_view.insertRow(0)
        self.themes_view.setItem(0,0,QTableWidgetItem(values_add_themes))
    def deleter_themes_view(self):
        values_deleter_themes = self.themes_view.selectedItems()[0].text()
        self.themes_view.removeRow(self.themes_view.currentRow())
        self.themes_select_view.insertRow(0)
        self.themes_select_view.setItem(0,0,QTableWidgetItem(values_deleter_themes))

    def add_lien(self):
        cur=login_base()
        maxrow=self.table_lien.rowCount()
        self.table_lien.insertRow(maxrow)

        table = layer.dataProvider().uri().table()
        schema = layer.dataProvider().uri().schema()

        if self.taille_line.text() == '':
            sql_sizefile = """SELECT pg_size_pretty(pg_total_relation_size('"""+schema+'.'+table+"""'));"""
            try:
                cur.execute(sql_sizefile)
                boolean = True

            except:
                boolean = False

            if boolean == True:
                size_file = (cur.fetchall())[0][0]
            else:
                size_file = ''

        else:
            size_file = self.taille_line.text()

        self.table_lien.setItem(maxrow,0,QTableWidgetItem('new_value'))
        self.table_lien.setItem(maxrow,1,QTableWidgetItem(self.type_box.currentText()))
        self.table_lien.setItem(maxrow,2,QTableWidgetItem(self.url_line.text()))
        self.table_lien.setItem(maxrow,3,QTableWidgetItem(self.mime_box.currentText()))
        self.table_lien.setItem(maxrow,4,QTableWidgetItem(self.format_box.currentText()))
        self.table_lien.setItem(maxrow,5,QTableWidgetItem(str(size_file)))

        global array_link
        array_link += "('"+ table +"','"+ schema +"','"+ self.type_box.currentText() +"','"+ self.url_line.text() +"','"+ self.mime_box.currentText() +"','"+ self.format_box.currentText() +"','"+ size_file +"'),"

        cur.close()

    def add_contact(self):
        maxrow=self.table_contact.rowCount()
        self.table_contact.insertRow(maxrow)

        self.table_contact.setItem(maxrow,0,QTableWidgetItem('new_value'))
        self.table_contact.setItem(maxrow,1,QTableWidgetItem(self.role_box.currentText()))
        self.table_contact.setItem(maxrow,2,QTableWidgetItem(self.nom_line.text()))
        self.table_contact.setItem(maxrow,3,QTableWidgetItem(self.organisation_box.currentText()))
        self.table_contact.setItem(maxrow,4,QTableWidgetItem(self.email_line.text()))
        self.table_contact.setItem(maxrow,5,QTableWidgetItem(self.telephone_line.text()))

        table = layer.dataProvider().uri().table()
        schema = layer.dataProvider().uri().schema()

        global array_contact
        array_contact += "('"+ table +"','"+ schema +"','"+ self.role_box.currentText() +"','"+ self.nom_line.text() +"','"+ self.organisation_box.currentText() +"','"+ self.email_line.text() +"','"+ self.telephone_line.text() +"'),"

    def delete_lien(self):

        global uid_delete_list_link,array_link
        lien_uid = self.table_lien.item(self.table_lien.currentRow(),0).text()
        self.table_lien.removeRow(self.table_lien.currentRow())
        if lien_uid == 'new_value':
            position = self.table_lien.currentRow()
            if position < 0:
                position=position+1
            run_x = 0
            while position >= run_x:
                #print(position,run_x)
                if run_x == 0:
                    debut = array_link.find("(")
                else:
                    debut = array_link.find("(",fin+1)
                fin = array_link.find(")",debut)
                #print(debut,fin)
                if run_x == 50:
                    break
                run_x+=1
            #print(array_link[fin+1:])
            if debut <= 0:
                debut = 1
                fin+= 1
            array_link = array_link[:debut-1]+array_link[fin+1:]
            #print('a:',array_link)
        else:
            uid_delete_list_link += "'"+lien_uid+"',"

    def delete_contact(self):
        global uid_delete_list_contact,array_contact
        contact_uid = self.table_contact.item(self.table_contact.currentRow(),0).text()
        self.table_contact.removeRow(self.table_contact.currentRow())
        if contact_uid == 'new_value':
            position = self.table_contact.currentRow()
            if position < 0:
                position=position+1
            #print('p:',position)
            run_x = 0
            while position >= run_x:
                if run_x == 0:
                    debut = array_contact.find("(")
                else:
                    debut = array_contact.find("(",fin+1)
                fin = array_contact.find(")",debut)
                #print(debut,fin)
                if run_x == 50:
                    break
                run_x+=1
            #print(array_contact[fin+1:])
            if debut <= 0:
                debut = 1
                fin+= 1
            array_contact = array_contact[:debut-1]+array_contact[fin+1:]
            #print('a:',array_contact)
        else:
            uid_delete_list_contact += "'"+contact_uid+"',"


    def fletch_ref(self):
        cur=login_base()

        SQL_categories="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.categories' ORDER BY code,item_order;"""
        SQL_themes="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.themes' ORDER BY label_fr;"""
        SQL_langue="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.langue';"""
        SQL_encodage="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.encodage';"""
        SQL_frequency="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.publication_frequency' ORDER BY label_fr;"""
        SQL_confidentiality="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.confidentiality' ORDER BY label_fr;"""
        SQL_license="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.license' ORDER BY label_fr;"""
        SQL_type="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.type' ORDER BY label_fr;"""
        SQL_mime="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.mime' ORDER BY label_fr;"""
        SQL_format="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.format' ORDER BY label_fr;"""
        SQL_role="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'contact.contact_role' ORDER BY label_fr;"""
        SQL_organisation="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'contact.organisation' ORDER BY label_fr;"""

        cur.execute(SQL_categories)
        categories_list=cur.fetchall()
        cur.execute(SQL_themes)
        themes_list=cur.fetchall()
        cur.execute(SQL_langue)
        langue_list=cur.fetchall()
        cur.execute(SQL_encodage)
        encodage_list=cur.fetchall()

        cur.execute(SQL_frequency)
        frequency_list=cur.fetchall()
        cur.execute(SQL_confidentiality)
        confidentiality_list=cur.fetchall()
        cur.execute(SQL_license)
        license_list=cur.fetchall()

        cur.execute(SQL_type)
        type_list=cur.fetchall()
        cur.execute(SQL_mime)
        mime_list=cur.fetchall()
        cur.execute(SQL_format)
        format_list=cur.fetchall()
        cur.execute(SQL_role)
        role_list=cur.fetchall()
        cur.execute(SQL_organisation)
        organisation_list=cur.fetchall()

        return categories_list,themes_list,langue_list,encodage_list,frequency_list,confidentiality_list,license_list,type_list,mime_list,format_list,role_list,organisation_list

        cur.close()

    def py_import_xml(self):
        folder = QFileDialog.getOpenFileName()
        if folder:
            folder=folder[0]
            if folder[len(folder)-4:] == '.xml' :
                print('is .xml')
    def issues_open(self):
        self.issues = CenRa_Issues()
        self.issues.show()
