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


def update_package():
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name

    headers = {"User_Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0"}
    payload = {"product" : "ezcast","category" : "windows", "lang" : "EN"}
    api_url = "https://www.ezcast.com/api/resource/get"

    response = requests.post(api_url, headers = headers, data = payload).json()
    download_url = response["data"][0]["path"]
    latest_bin = download_url.split("/")[-1]
    latest_bin_extension = latest_bin.rsplit('.', 1)[-1]
    version = latest_bin.split("-")[-1].rsplit(".", 1)[0]

    # Downloading latest binaries
    print(f"Latest {app_name} version is: {version}")
    print(f"Download URL is: {download_url}")
    if not isfile(latest_bin):
        print(f"Downloading: {latest_bin}")
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print(f"Binary is present: {latest_bin}")

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print(f"Software version updated (from: {control.get_software_version()} to: {Version(version)})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({Version(version)})")

    for f in glob.glob(f'*.{latest_bin_extension}'):
        if f != latest_bin:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated