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

# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls


def update_package():
    result = False
    proxies = get_proxies()
    
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    git_repo = "mapeditor/tiled"
    url_api = "https://api.github.com/repos/%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('.msi') and "Windows-10+" in download["name"] and "_x86_64.msi" in download["name"]:
            url_dl = download["browser_download_url"]
            version = json_load["tag_name"].replace("v","")
            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('*.msi'):
        if f != filename:
            remove_file(f)
    
    control.set_software_version(version)
    control.save_control_to_wapt()