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


def install():
    bin_name = glob.glob("VSCodeSetup-*.exe")[0]
    app_uninstallkey = "Microsoft Visual Studio Code"

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

    # Adding Firewall Rules
    app_name = "Visual Studio Code"
    app_path = makepath(installed_softwares(name=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)
