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


def install():
    # Initializing variables
    app_uninstallkey = "{6DB8C365-E719-4BA5-9594-10DFC244D3FD}_is1"
    app_dir = makepath(programfiles32, "Gyazo")
    package_version = control.version.split("-")[0]
    bin_name = "Gyazo-%s.exe" % package_version

    def get_version_soft(key):
        return key["name"].split(" ")[1]

    # Installing the package
    print("Installing: %s" % bin_name)
    install_exe_if_needed(bin_name, silentflags="/VERYSILENT /SUPPRESSMSGBOXES /NORESTART", key=app_uninstallkey, min_version=package_version, get_version=get_version_soft)

    if not installed_softwares(uninstallkey=app_uninstallkey)[0]["version"]:
        # Create silent uninstall command in registry
        app_uninstallkey_quiet = installed_softwares(uninstallkey=app_uninstallkey)[0]["uninstall_string"] + "/VERYSILENT"
        # Add in registry
        register_uninstall(app_uninstallkey, app_uninstallkey_quiet, display_version=package_version)
    # Remove updater
    remove_file(makepath(app_dir, "GyazoUpdate.exe"))

    for soft in ["Gyazowin.exe", "GyazoGIF.exe", "GyazoReplay.exe"]:
        create_programs_menu_shortcut(soft.split(".exe")[0], makepath(app_dir, soft))
    create_programs_menu_shortcut("Gyazo Settings", makepath(app_dir, "GyStation.exe"), "/option")


def uninstall():

    for soft in ["Gyazowin.exe", "GyazoGIF.exe", "GyazoReplay.exe"]:
        remove_programs_menu_shortcut(soft.split(".exe")[0])
    remove_programs_menu_shortcut("Gyazo Settings")


def get_version_from_binary(filename, parameter="ProductVersion"):
    if filename.endswith(".msi"):
        return get_msi_properties(filename)[parameter]
    else:
        return get_file_properties(filename)[parameter]


def remove_outdated_binaries(version, list_extensions=["exe", "msi", "deb", "rpm", "dmg", "pkg", "zip"], list_filename_contain=None):
    if type(list_extensions) != list:
        list_extensions = [list_extensions]
    if list_filename_contain:
        if type(list_filename_contain) != list:
            list_filename_contain = [list_filename_contain]
    list_extensions = ["." + ext for ext in list_extensions if ext[0] != "."]
    for file_ext in list_extensions:
        for bin_in_dir in glob.glob("*%s" % file_ext):
            if not version in bin_in_dir:
                remove_file(bin_in_dir)
            if list_filename_contain:
                for filename_contain in list_filename_contain:
                    if not filename_contain in bin_in_dir:
                        remove_file(bin_in_dir)

