# -*- coding: utf-8 -*-
from setuphelpers import *
from setupdevhelpers import *
from string import ascii_lowercase
import re

# Convertit une lettre en son numéro de position dans l'alphabet "ex: a=1, b=2 ..."
def letter_to_number(c):
        return str(ascii_lowercase.index(c.lower()) + 1)

# Remplace chaque lettre trouvée par son numéro "match.group(0) est la lettre trouvée"
def replace_letters_with_numbers(match):
    return letter_to_number(match.group(0))

def update_package():
    # Declaring local variables
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name

    git_repo = "Test-Compta-Demat"
    url_api = "https://api.github.com/repos/DGFiP/%s/releases/latest" % git_repo

    # Getting latest version information from official sources
    print("API used is: %s" % url_api)
    json_load = json.loads(wgets(url_api, proxies=proxies))

    for download in json_load["assets"]:
        if download["browser_download_url"].endswith("x86_64.exe") :
            url_dl = download["browser_download_url"]
            tag = json_load["tag_name"].split("-")[-1]
            version = re.sub(r'[a-zA-Z]', replace_letters_with_numbers, tag)
            version = re.sub(r'^(\d+\.\d+\.)(\d{2})(\d)$', r'\1\2.\3', version)
            filename = download["name"]
            break

    if not isfile(filename):
        package_updated = True
        wget(url_dl, filename, proxies=proxies)

    # nettoyer les fichiers temporaires
    for f in glob.glob("*.exe"):
        if f != filename:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()