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


# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls
bin_contains = "code_"
package_name = "code"
app_dist_source_path = "/etc/apt/sources.list.d/vscode.list"

if is_debian() and Version(get_debian_version()) >= Version("13"):
    app_dist_source_path = "/etc/apt/sources.list.d/vscode.sources"


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

    update_apt()
    # missing dependance in debian package
    install_apt("gnupg")
    # Installing the software
    print("Installing: %s" % bin_name)
    install_deb(bin_name)

    # Deleting the distribution source file of the application
    if isfile(app_dist_source_path):
        print("Removing: %s" % app_dist_source_path)
        remove_file(app_dist_source_path)


def uninstall():
    # Uninstalling the package
    print("Uninstalling: %s" % package_name)
    uninstall_apt(package_name)


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_home_directory(), ".config", "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.strip(","))
    if not isdir(user_conf_dir):
        mkdirs(user_conf_dir)
    if not isfile(user_conf_file):
        print("Creating: %s" % user_conf_file)
        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: %s" % user_conf_file)
        json_write_file(user_conf_file, new_user_conf_data)
