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


def install():
    version = control.get_software_version()

    # Uninstalling older versions of the software
    for to_uninstall in installed_softwares(name=r"\bvokoscreenNG\b"):
        if Version(to_uninstall["version"]) < Version(version) or force:
            print("Removing: %s (%s)" % (to_uninstall["name"], to_uninstall["version"]))
            killalltasks(control.impacted_process.split(","))
            run(uninstall_cmd(to_uninstall["key"]))
            wait_uninstallkey_absent(to_uninstall["key"])
            time.sleep(10)

    # uninstallkey dynamique ... beurk
    install_exe_if_needed(
        "vokoscreenNG-%s-win64.exe" % version,
        "in -c --al --am AllUsers=true",
        min_version=version,
        name="vokoscreenNG",
    )

    # force QuietUninstallString
    install_loc_bvokoscreen = installed_softwares(name=r"\bvokoscreenNG\b")[0]["install_location"]
    exe_bvokoscreen = makepath(install_loc_bvokoscreen, "Uninstall.exe")

    nb = 0
    while not isfile(exe_bvokoscreen):
        nb = nb + 1
        if nb > 60:
            error("%s not found" % exe_bvokoscreen)
        time.sleep(1)

    time.sleep(10)
    quietuninstallstring = '"%s" pr -c' % exe_bvokoscreen

    registry_setstring(
        HKEY_LOCAL_MACHINE,
        r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\%s" % uninstallkey[0],
        "QuietUninstallString",
        quietuninstallstring,
    )

    remove_desktop_shortcut("vokoscreenNG-%s" % version)
