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

silent_args_dict = {"NOGOOGLEUPDATING": 1, "NOGOOGLEUPDATEPING": 1}
app_scheduled_tasks = ["GoogleUpdateTaskMachineCore", "GoogleUpdateTaskMachineUA"]
app_services = ["GoogleChromeElevationService", "gupdate", "gupdatem"]


def install():
    # Declaring local variables
    package_version = control.version.split("-", 1)[0]
    bin_name = "googlechromestandaloneenterprise.msi"
    skip = False

    uninstallkey_from_file = get_msi_properties(bin_name)["ProductCode"]

    def get_version_chrome(key):
        for path_test in [programfiles,programfiles32]:
            chrome_bin_path = makepath(path_test, "Google", "Chrome", "Application","chrome.exe")
            if isfile(chrome_bin_path):
                return get_file_properties(chrome_bin_path)["ProductVersion"]
        return '0'

    if windows_version() < WindowsVersions.Windows10:
        # Uninstalling newer versions of the software
        for to_uninstall in installed_softwares(name="^Google Chrome$"):
            if Version(to_uninstall["version"]) > Version(control.get_software_version()) or force:
                print("Removing: %s (%s)" % (to_uninstall["name"], to_uninstall["version"]))
                try:
                    killalltasks(control.get_impacted_process_list())
                    run(uninstall_cmd(to_uninstall["key"]))
                    wait_uninstallkey_absent(to_uninstall["key"])
                except Exception as e:
                    print(e)
                    print("Remove failed: %s (%s)\nContinuing..." % (to_uninstall["name"], to_uninstall["version"]))

    # Installing the package
    if Version(get_version_chrome(None)) >= Version(package_version):
        if uninstall_key_exists(uninstallkey_from_file):
            uninstallkey.append(uninstallkey_from_file)
        skip = True

    if (not skip) or force:
        print("Installing: %s" % bin_name)
        install_msi_if_needed(
            bin_name,
            properties=silent_args_dict,
            min_version=package_version,
            get_version=get_version_chrome,
        )

    # Disabling application scheduled tasks
    for task in get_all_scheduled_tasks():
        if task.split("{")[0] in app_scheduled_tasks:
            if task_exists(task):
                try:
                    disable_task(task)
                except:
                    print("Unable to disable the task: %s" % task)

    # Changing default start mode of the application services
    for service_name in app_services:
        set_service_start_mode(service_name, "Manual")

    # Disabling Google Chrome Auto-Update and Telemetry
    registry_setstring(HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\Google\Update", "UpdateDefault", 0, type=REG_DWORD)
    registry_setstring(HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\Google\Update", "DisableAutoUpdateChecksCheckboxValue", 1, type=REG_DWORD)
    registry_setstring(HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\Google\Update", "AutoUpdateCheckPeriodMinutes", 0, type=REG_DWORD)
    registry_setstring(HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\Explorer\DisallowRun", "chrome_telemetry", "Software_Reporter_Tool.exe", type=REG_SZ)

    # # Adding master preferences file (instead, we recommend that you to create a package like tis-chrome-config)
    # filecopyto("master_preferences", chrome_app_path)


def uninstall():
    if isdir(makepath(programfiles32, "Google", "Chrome", "Application")):
        chrome_app_path = makepath(programfiles32, "Google", "Chrome", "Application")
    else:
        chrome_app_path = makepath(programfiles, "Google", "Chrome", "Application")
    chrome_bin_path = makepath(chrome_app_path, "chrome.exe")

    # Uninstalling the package
    if uninstall_key_exists("Google Chrome"):
        if not "msiexec" in " ".join(list(uninstall_cmd("Google Chrome"))).lower():
            versionsoft = get_file_properties(chrome_bin_path)["ProductVersion"]
            run(
                '"%s" --uninstall --system-level --force-uninstall --qn'
                % makepath(install_location("Google Chrome"), versionsoft, "Installer", "setup.exe"),
                accept_returncodes=[19],
            )


def session_setup():
    # Declaring local variables
    swreporter_path = makepath(user_local_appdata, "Google", "Chrome", "User Data", "SwReporter")
    if isdir(swreporter_path):
        print("Removing: %s" % swreporter_path)
        remove_tree(swreporter_path)
