# -*- coding: utf-8 -*-
from setuphelpers import *
import json
import time
import sys

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
from setupdevhelpers import *


default_allow_prerelease = False


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

    ext_uid_name = ""
    with open("setup.py", "r", encoding="utf8") as f:
        for line in f.readlines():
            if line.startswith("ext_uid_name"):
                ext_uid_name = line.split("=")[1].split('"')[1]
                break
    old_ext_uid_name = ext_uid_name

    # Getting the extension's webpage url
    url = control.sources
    if not url:
        ext_uid_name = ask_input(
            control.package,
            "Enter the extension UID name (Ex: ms-vscode-remote.remote-wsl) or the link from the Visual Studio Marketplace (Ex: https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl)",
            url,
            raise_error=True,
        ).split("itemName=")[-1]
        url = "https://marketplace.visualstudio.com/items?itemName=" + ext_uid_name
    else:
        ext_uid_name = url.split("itemName=")[-1]
    ext_publisher = ext_uid_name.split(".")[0]
    control.sources = url
    control.save_control_to_wapt()

    # Getting latest data from official sources
    print("URL used is %s" % url)
    for bs_search in bs_find_all(url, "script", "type", "application/json", proxies=proxies):
        if bs_search.string.startswith("{"):
            json_data = json.loads(bs_search.string)
            break

    version = json_data["Resources"]["Version"]

    # # Asking the user if a prerelease version bother him
    # skip_prerelease = False
    # prerelease_detected = True
    # if Version(version) > Version(control.get_software_version()) and not params.get("running_as_luti"):
    #     if json_data["ExtensionProperties"].get("Microsoft.VisualStudio.Code.PreRelease", "") == "true":
    #         if (
    #             ask_message(
    #                 ext_uid_name,
    #                 "The latest version of the extension is in prerelease, do you want to use it? Otherwise it will use the latest version detected by Luti.",
    #                 # "The latest version of the extension is in prerelease, do you want to use it? (not recommended)",
    #                 flags=(4 + 32),
    #                 raise_error=True,
    #             )
    #             == 7
    #         ):
    #             skip_prerelease = True
    #     else:
    #         prerelease_detected = False
    # if not default_allow_prerelease:
    #     if skip_prerelease or params.get("running_as_luti"):
    #         # You can manually check release version here by replacing the following code (by default it check on Luti)
    #         try:
    #             luti_package_name = "tis-vscode-%s" % (ext_uid_name.split(".", 1)[-1])
    #             if params.get("running_as_luti"):
    #                 version = wgets("https://srvluti.ad.tranquil.it/check_update_result_update.json", proxies=proxies, as_json=True)[
    #                     luti_package_name
    #                 ]
    #             else:
    #                 version = wgets("https://luti.tranquil.it/check_update_result_update.json", proxies=proxies, as_json=True)[luti_package_name]
    #         except:
    #             error(
    #                 f"{luti_package_name} is not monitored on: https://luti.tranquil.it - You can manually check the release version by editing this package or using the prerelease version."
    #             )
    #     elif not prerelease_detected:
    #         print("INFO: Latest version of this extension in prerelease.")
    #         # error("ERROR: The latest version of this extension is in prerelease. Please wait for it to be fully released.")
    #     else:
    #         print("INFO: Latest version of this extension is a release.")

    # Creating download_url
    #version = "2024.2.1"  # temp fix
    download_url = "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/%s/vsextensions/%s/%s/vspackage" % (
        ext_publisher,
        json_data["Resources"]["ExtensionName"],
        version,
    )
    latest_bin = ext_uid_name + "-%s.vsix" % version

    # Downloading latest binaries
    print("Latest %s version is: %s" % (control.name, version))
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        content = requests.get(download_url, stream=True)
        nb_wait = 0
        max_wait = 3600
        while str(content.status_code) == "429":
            timewait = int(content.headers["Retry-After"])
            print("Wait %s" % timewait)
            nb_wait = nb_wait + timewait
            if nb_wait > max_wait:
                error("Max wait ...")
            time.sleep(timewait)
            content = requests.get(download_url, stream=True)

        with open(latest_bin, "wb") as f:
            for chunk in content.iter_content(chunk_size=1024 * 1024):
                f.write(chunk)
    else:
        print("Binary is present: %s" % latest_bin)

    # Deleting outdated binaries
    remove_outdated_binaries(latest_bin, list_extensions=["vsix"])

    # Completing control file
    if not old_ext_uid_name or old_ext_uid_name != ext_uid_name:
        # control.name
        control_name = bs_find(url, "title", proxies=proxies).text
        control_name = control_name.split(" - Visual Studio Marketplace")[0].strip()
        control_name = complete_control_name(control, control_name, silent=params.get("running_as_luti"))

        # control.package
        package_prefix = control.package.split("-")[0]
        control_package = package_prefix + "-vscode-" + ext_uid_name.split(".", 1)[-1]
        complete_control_package(control, control_package, silent=params.get("running_as_luti"))

        # control.description
        complete_control_description(control, blank_str="update_package", silent=params.get("running_as_luti"))

        # control.categories
        control.categories = "Extension"

        # icon.png
        unzip(latest_bin)
        unzipped_dir = latest_bin.rsplit(".", 1)[0]
        new_icon_png = makepath(unzipped_dir, "extension", "icon.png")
        if isfile(new_icon_png):
            filecopyto(makepath(unzipped_dir, "extension", "icon.png"), "WAPT")

        # control.installed_size
        control.installed_size = get_size(unzipped_dir)
        control.save_control_to_wapt()

        remove_tree(unzipped_dir)

    # Updating setup.py ext_uid_name variable
    new_lines = []
    with open("setup.py", "r", encoding="utf8") as f:
        for line in f.readlines():
            if line.startswith("ext_uid_name"):
                line = 'ext_uid_name = "%s"\n' % ext_uid_name
            new_lines.append(line)
    with open("setup.py", "w", encoding="utf8", newline="\n") as f:
        f.writelines(new_lines)

    # Changing version of the package
    if Version(version, 4) > Version(control.get_software_version(), 4):
        print("Software version updated (from: %s to: %s)" % (control.get_software_version(), Version(version)))
        package_updated = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating or not update-package-sources
    return package_updated
