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

# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls
config_dir = makepath(programfiles, "Mattermost", "config")
bin_contains = "mattermost-desktop"
install_appdata = makepath(user_local_appdata(), "Programs", "mattermost-desktop")

def install():
    # Declaring local variables
    package_version = control.get_software_version()
    bin_name = glob.glob("*%s*.msi" % bin_contains)[0]

    for soft in installed_softwares("Mattermost"):
        if not isfile(makepath(programfiles(),"mattermost-desktop","Mattermost.exe")):
            killalltasks("Mattermost.exe")
            if uninstall_key_exists(soft['key']):
                run(uninstall_cmd(soft['key']))

    install_msi_if_needed(bin_name, min_version=package_version,properties={"ALLUSERS":1,"DISABLEAUOTUPDATE":1} )

    mkdirs(config_dir)
    if isfile("config.json"):
        filecopyto("config.json", config_dir)

    remove_desktop_shortcut("Mattermost")


def session_setup():
    # Declaring local variables


    # Copy Config
    if isfile(makepath(config_dir, "config.json")):
        config_user = makepath(user_appdata, "Mattermost")
        mkdirs(config_user)
        filecopyto(makepath(config_dir, "config.json"), config_user)

    # Remove AppData Installation
    if isdir(install_appdata):
        killalltasks("Mattermost.exe")
        try:
            cmd_uninstall_appdata = '"' + makepath(install_appdata, 'Uninstall Mattermost.exe" /currentuser /S')
            run(cmd_uninstall_appdata)
        except:
            print("Not installed in this User AppData, cleaning")
        remove_tree(install_appdata)
