"""Tools to work with resource files."""

import configparser
import shutil
import tempfile
import base64
import psycopg2
import psycopg2.extras
from os.path import abspath, join, pardir, dirname
from qgis.PyQt.QtWidgets import QApplication
from qgis.PyQt import uic

__copyright__ = "Copyright 2019, 3Liz"
__license__ = "GPL version 3"
__email__ = "info@3liz.org"
__revision__ = "$Format:%H$"


def plugin_path(*args):
    """Get the path to plugin root folder.

    :param args List of path elements e.g. ['img', 'logos', 'image.png']
    :type args: str

    :return: Absolute path to the plugin path.
    :rtype: str
    """
    path = dirname(dirname(__file__))
    path = abspath(abspath(join(path, pardir)))
    for item in args:
        path = abspath(join(path, item))

    return path


def plugin_name():
    """Return the plugin name according to metadata.txt.

    :return: The plugin name.
    :rtype: basestring
    """
    metadata = metadata_config()
    name = metadata["general"]["name"]
    return name


def metadata_config() -> configparser:
    """Get the INI config parser for the metadata file.

    :return: The config parser object.
    :rtype: ConfigParser
    """
    path = plugin_path("metadata.txt")
    config = configparser.ConfigParser()
    config.read(path, encoding='utf8')
    return config


def plugin_test_data_path(*args, copy=False):
    """Get the path to the plugin test data path.

    :param args List of path elements e.g. ['img', 'logos', 'image.png']
    :type args: str

    :param copy: If the file must be copied into a temporary directory first.
    :type copy: bool

    :return: Absolute path to the resources folder.
    :rtype: str
    """
    path = abspath(abspath(join(plugin_path(), "test", "data")))
    for item in args:
        path = abspath(join(path, item))

    if copy:
        temp = tempfile.mkdtemp()
        shutil.copy(path, temp)
        return join(temp, args[-1])
    else:
        return path


def resources_path(*args):
    """Get the path to our resources folder.

    :param args List of path elements e.g. ['img', 'logos', 'image.png']
    :type args: str

    :return: Absolute path to the resources folder.
    :rtype: str
    """
    path = abspath(abspath(join(plugin_path(), "CenRa_PAGERENDER\\tools")))
    for item in args:
        path = abspath(join(path, item))
    return path


def load_ui(*args):
    """Get compile UI file.

    :param args List of path elements e.g. ['img', 'logos', 'image.png']
    :type args: str

    :return: Compiled UI file.
    """
    ui_class, _ = uic.loadUiType(resources_path("ui", *args))

    return ui_class

def login_base(take=None):
    from CenRa_METABASE.tools.PythonSQL import host,port,dbname,password,os_user
    first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbname+" user=first_cnx password=" + password)
    first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
    first_cur.execute("SELECT mdp_w, login_w FROM pg_catalog.pg_user t1, admin_sig.vm_users_sig t2 WHERE t2.oid = t1.usesysid AND (login_w = '" + os_user + "' OR login_w = '" + os_user + "')")
    res_ident = first_cur.fetchone()

    mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
    user = res_ident[1]

    con = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbname+" user=" + user + " password=" + mdp)
    
    cur = con.cursor(cursor_factory = psycopg2.extras.DictCursor)
    first_conn.close()

    if take:
        return cur,con
    else:
        return cur
def send_issues(url,titre,body,labels):
    import requests
    import json
    import os
    import qgis

    usr = os.environ['USERNAME']
    token = '9d0a4e0bea561710e0728f161f7edf4e5201e112'
    url=url+'?token='+token

    headers = {'Authorization': 'token ' + token,'accept': 'application/json','Content-Type': 'application/json'}


    payload = {'title': titre, 'body': body, 'labels': labels}
    try:
        urllib.request.urlopen('https://google.com')
        binar = True
    except:
        binar = False
        r = ''
    if binar:
        r = requests.post(url, data=json.dumps(payload), headers=headers)
    return r

def maj_verif(NAME):
    import qgis
    import urllib.request
    iface = qgis.utils.iface
    from qgis.core import Qgis

    url = qgis.utils.pluginMetadata(NAME,'repository')
    #URL = url+'/raw/branch/main/plugins.xml'
    URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/releases/plugins.xml'
#    print(URL)
    version = qgis.utils.pluginMetadata(NAME,'version')
    len_version = len(version)
    try:
        urllib.request.urlopen('https://google.com')
        binar = True
    except:
        binar = False
    if binar:
        version_web = str(urllib.request.urlopen(URL).read())
        plugin_num = version_web.find(NAME)
        valeur_version_web = version_web.find('<version>',plugin_num)+9
        version_plugin = version_web[valeur_version_web:valeur_version_web+len_version]
        if version_plugin != version:
            iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30)
    else:
        iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30)

def tr(text, context="@default"):
    return QApplication.translate(context, text)

def devlog(NAME):
    import qgis
    devmaj = '<head><style>* {margin:0; padding:0; }</style></head>'
    devmaj = devmaj+qgis.utils.pluginMetadata(NAME,'changelog')
    return devmaj