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


"""
    The .exe of mullvad browser installs in the user appdata. There is an option to install it in
    standalone but it is only accessible via GUI so we are doing a portable install

    https://mullvad.net/fr/help/install-mullvad-browser#windows-install

    Before using this package, make sure that the profiles are saved during an update
"""

app_name = "MullvadBrowser"
app_dir = makepath(programfiles, app_name)
app_path = makepath(app_dir, f"mullvadbrowser.exe")
icon_path = app_path
audit_version = False


def get_installed_version(app_path):
    return get_file_properties(app_path).get("FileVersion", "")


def install():
    # Declaring local variables
    zip_name = glob.glob(f"mullvad-browser-windows-x86_64-*.exe")[0]
    unzip_dest = app_name
    unzipped_dir = app_name

    # Installing software
    killalltasks(ensure_list(control.impacted_process))
    if isdir(app_dir) and force:
        remove_tree(app_dir)
    mkdirs(app_dir)
    print("Extracting: %s to: %s" % (zip_name, app_dir))
    unzip_with_7zip(zip_name, unzip_dest)
    copytree2(unzipped_dir, app_dir, onreplace=default_overwrite)

    # Creating custom shortcuts
    create_desktop_shortcut(app_name, target=app_path)
    create_programs_menu_shortcut(app_name, target=app_path)


def audit():
    # Auditing software
    audit_status = "OK"
    installed_version = get_installed_version(app_path)
    if Version(installed_version) < Version(control.get_software_version()) and audit_version:
        print("%s is installed in version (%s) instead of (%s)" % (app_name, installed_version, control.get_software_version()))
        audit_status = "WARNING"
    elif isdir(app_dir) and not dir_is_empty(app_dir):
        print("%s (%s) is installed" % (app_name, installed_version))
        audit_status = "OK"
    else:
        print("%s is not installed" % app_name)
        audit_status = "ERROR"
    return audit_status


def uninstall():
    # Uninstalling software
    killalltasks(ensure_list(control.impacted_process))
    if isdir(app_dir):
        remove_tree(app_dir)

    # Removing shortcuts
    remove_desktop_shortcut(app_name)
    remove_programs_menu_shortcut(app_name)
