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

bin_contains = "Opera_"


def update_package():
    # Declaring local variables
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    download_url = "https://get.geo.opera.com/pub/opera/desktop/%s/win/"

    # Getting latest version from official sources
    re_versions = re.compile('<a href="([\d\.]*)/">')
    index = wgets("https://get.geo.opera.com/pub/opera/desktop/", proxies=proxies)

    for versionopera in sorted(re_versions.findall(index),key=lambda p:(Version(p)),reverse=True):

        if control.architecture == "x64":
            latest_bin = bin_contains + "%s_Setup_x64.exe" % versionopera
        else:
            latest_bin = bin_contains + "%s_Setup.exe" % versionopera

        if not requests.head((download_url % versionopera) + latest_bin, proxies=proxies).status_code == 404:
            version = versionopera
            break

    print("Latest %s version is: %s" % (app_name, version))
    print("Download URL is: %s" % (download_url % version))

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

        # Checking version from file
        version_from_file = get_product_props(latest_bin)["ProductVersion"]
        if Version(version) != Version(version_from_file) and version_from_file != "":
            version = version_from_file
        else:
            print("Binary file version corresponds to online version")

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

    # Deleting outdated binaries
    remove_outdated_binaries(version)

    # Validating or not update-package-sources
    return result
