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



def update_package():
    # Initializing variables
    bin_name_sub = "Gyazo-%s.exe"
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    url = "https://gyazo.com/download"
    bin_end = bin_name_sub.split("%s")[-1]
    # bin_start = bin_name_sub.split('%s')[0]

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(
        url,
        "a",
        "id",
        "download_btn",
        headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0"},
        proxies=proxies,
    ):
        if bs_search["href"].split("/")[-1].endswith(bin_end):
            latest_bin = bs_search["href"].split("/")[-1]
            version = bs_search["href"].split("-")[-1].split(bin_end)[0]
            url_dl = bs_search["href"]
            break

    print("Latest %s version is: %s" % (app_name, version))
    print("Download url is: %s" % url_dl)

    # Downloading latest binaries
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(url_dl, latest_bin, proxies=proxies)

        # Checking version from file
        version_from_file = get_version_from_binary(latest_bin)
        if version != version_from_file:
            os.rename(latest_bin, bin_name_sub % version_from_file)
            version = version_from_file

        # Changing version of the package
        control.version = "%s-%s" % (version, control.version.split("-", 1)[-1])
        control.save_control_to_wapt()
        print("Changing package version to: %s in WAPT\\control" % control.version)

    # Deleting outdated binaries
    remove_outdated_binaries(version)

