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


def install():
    bin_name = glob.glob("VSCodeSetup-*.exe")[0]
    if control.architecture == "x64":
        app_uninstallkey = "{EA457B21-F73E-494C-ACAB-524FDE069978}_is1"
    else:
        app_uninstallkey = "{F8A2A208-72B3-4D61-95FC-8A65D340689B}_is1"

    install_exe_if_needed(
        bin_name,
        silentflags='/verysilent /mergetasks="!runcode"',
        key=app_uninstallkey,
        min_version=control.get_software_version(),
        timeout=600,
    )

    # Adding Firewall Rules
    app_name = "Visual Studio Code"
    app_path = makepath(installed_softwares(uninstallkey=app_uninstallkey)[0]["install_location"], "code.exe")
    run_powershell(f'Remove-NetFirewallRule -DisplayName "{app_name}" -ErrorAction SilentlyContinue', accept_returncodes=[0, 1, 3010])
    run_powershell(
        f'New-NetFirewallRule -DisplayName "{app_name}" -Group "{app_name}" -Program "{app_path}" -Action Allow -Direction Inbound -Enabled True'
    )


def session_setup():
    print("Disabling: Telemetry, automatic updates, surveys")

    # Configuration procedure: https://supunkavinda.blog/vscode-editing-settings-json
    # C:\Users\username\AppData\Roaming\Code\User\settings.json

    # Initializing variables
    user_conf_dir = makepath(user_appdata, "Code", "User")
    user_conf_file = makepath(user_conf_dir, "settings.json")
    user_conf_content = r"""{
    "update.mode": "none",
    "update.enableWindowsBackgroundUpdates": false,
    "update.showReleaseNotes": false,
    "telemetry.telemetryLevel": "off",
    "typescript.surveys.enabled": false,
    "extensions.autoCheckUpdates": false,
    "extensions.autoUpdate": false
}"""

    user_conf_data = json.loads(user_conf_content)
    if not isdir(user_conf_dir):
        mkdirs(user_conf_dir)
    if not isfile(user_conf_file):
        print("Creating: settings.json in: %s" % user_conf_dir)
        json_write_file(user_conf_file, user_conf_data)
    else:
        new_user_conf_data = json_load_file(user_conf_file)
        new_user_conf_data.update(user_conf_data)
        print("Updating: settings.json in: %s" % user_conf_dir)
        json_write_file(user_conf_file, new_user_conf_data)
