# -*- coding: utf-8 -*-
from setuphelpers import *
import msilib
import json
import waptlicences


def update_package():
    # Declaring local variables
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name

    url_dl = "https://dl.google.com/tag/s/dl/chrome/install/googlechromestandaloneenterprise.msi"
    latest_bin = url_dl.split("/")[-1]

    # Downloading latest binaries
    print("Download url is: %s" % url_dl)

    if isfile(latest_bin):
        remove_file(latest_bin)

    print("Downloading: " + latest_bin)
    wget(url_dl, latest_bin, proxies=proxies)

    # Check signature bin
    expected_issuer = 'Google LLC'
    sign_name = waptlicences.check_msi_signature(latest_bin)[0]
    if sign_name != expected_issuer:
        error('Bad issuer %s != %s ' % (sign_name,expected_issuer))

    # Get version from description msi
    db = msilib.OpenDatabase(latest_bin, msilib.MSIDBOPEN_READONLY)
    db.GetSummaryInformation(1)
    description = db.GetSummaryInformation(1).GetProperty(6)
    version = ensure_unicode(description).split(" ", 1)[0]

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

    # Validating update-package-sources
    return result
