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

def remove_putty_if_install_with_exe():
    if uninstall_key_exists("PuTTY_is1"):
        killalltasks(control.impacted_process.split(","))
        # uninstaller cannot be silenced by design (cf putty.iss), so we remove stuff by hand
        # run('"%s" /VERYSILENT /SUPPRESSMSGBOXES' % os.path.join(programfiles32,'putty','unins000.exe'))
        if isdir(install_location("PuTTY_is1")):
            remove_tree(install_location("PuTTY_is1"))
        registry_delete(HKEY_LOCAL_MACHINE, "SOFTWARE\\Classes\\PuTTYPrivateKey", None)
        if iswin64():
            registry_delete(HKEY_LOCAL_MACHINE, "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\PuTTY_is1", None)
        else:
            registry_delete(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\PuTTY_is1", None)
        putty_link = makepath(winshell.programs(common=1), "PuTTY")
        if isdir(putty_link):
            remove_tree(putty_link)
        unregister_uninstall("Putty_is1")


def install():

    # Uninstalling the EXE versions of the software
    remove_putty_if_install_with_exe()
    # Initializing variables
    package_version = control.version.split("-", 1)[0]
    bin_name = glob.glob("putty-*-installer.msi")[0]

    # Force uninstalling older versions of the software
    for to_uninstall in installed_softwares(name="^PuTTY"):
        if to_uninstall["publisher"]=="Simon Tatham" and Version(to_uninstall["version"]) < Version(control.get_software_version()) or force:
            print("Removing: %s (%s)" % (to_uninstall["name"], to_uninstall["version"]))
            killalltasks(ensure_list(control.impacted_process))
            try:
                run(uninstall_cmd(to_uninstall["key"]))
                wait_uninstallkey_absent(to_uninstall["key"], max_loop=60, raise_on_timeout=True)
            except Exception as e:
                print(e)
                time.sleep(60)
                unregister_uninstall(to_uninstall["key"], win64app=to_uninstall["win64"])
                if isdir(to_uninstall["install_location"]):
                    remove_tree(to_uninstall["install_location"])

    # Installing the package
    install_msi_if_needed(
        bin_name,
        min_version=package_version,
    )


def session_setup():
    remove_user_programs_menu_folder("PuTTY (64-bit)")
    remove_user_programs_menu_folder("PuTTY")


def uninstall():
    remove_programs_menu_folder("PuTTY (64-bit)")
    remove_programs_menu_folder("PuTTY")


def remove_user_programs_menu_folder(folder):
    """Remove a folder from the start menu of current user

    Args:
        folder(str): folder to remove
    """
    user_programs_menu_folder = makepath(winshell.programs(common=0), folder)
    if isdir(user_programs_menu_folder):
        remove_tree(user_programs_menu_folder)
