# -*- coding: utf-8 -*-
from setuphelpers import *
import re
import json

def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    git_repo = "Amulet-Team/Amulet-Map-Editor"
    url_api = "https://api.github.com/repos/%s/releases" % 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))
    binariesfound = False

    # Filtering stable releases
    release = [r for r in json_load if not (r["draft"] or r["prerelease"])]
    if not release:
        raise Exception("No stable releases found")

    # Get latest release
    latest_release = sorted(release, key=lambda r: Version(r["tag_name"].lstrip("v")), reverse=True)[0]
    url_dl = "https://codeload.github.com/%s/zip/refs/tags/%s" % (git_repo, latest_release["tag_name"])
    version = latest_release["tag_name"].split('b')[0]
    filename = "Amulet.Map.Editor-v%s-portable.zip" % latest_release["tag_name"]
    binariesfound = True

    print("URL to download:", url_dl)
    print("Filename:", filename)

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

    # Clean files temp
    for f in glob.glob('*.zip'):
        if f != filename:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()