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


app_name = "TeamViewerQS"
bin_name = "TeamViewerQS.exe"
app_dir = makepath(programfiles32, app_name)
app_path = makepath(app_dir, "TeamViewerQS.exe")


def install():
    # Uninstalling software from old path
    uninstall_tvqs()

    # Installing software
    killalltasks(ensure_list(control.impacted_process))
    if isdir(app_dir) and force:
        remove_tree(app_dir)
    mkdirs(app_dir)
    filecopyto(bin_name, app_path)

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

    # Adding Firewall Rules
    remove_netfirewallrule(app_name)
    add_netfirewallrule(app_name, app_path, app_name, profile="Domain,Private", protocol="UDP")
    add_netfirewallrule(app_name, app_path, app_name, profile="Domain,Private", protocol="TCP")


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)

    # Removing Firewall Rules
    remove_netfirewallrule(app_name)


def uninstall_tvqs():
    bin_contains = "TeamViewerQS"
    app_name = "TeamViewerQS"
    app_dir = makepath(programfiles, app_name)

    # Uninstalling software
    killalltasks(control.get_impacted_process_list())
    if isdir(app_dir):
        remove_tree(app_dir)
    unregister_uninstall(app_name)

    # Removing shortcuts
    remove_desktop_shortcut(app_name)
    remove_programs_menu_shortcut(app_name)


def add_netfirewallrule(
    rule_name,
    app_path,
    group=None,
    direction="Inbound",
    profile=None,
    enabled=True,
    action="Allow",
    protocol=None,
):
    """
    Add a Windows Firewall rule using New-NetFirewallRule cmdlet in PowerShell for Windows 10 and newer,
    or netsh advfirewall for older Windows versions.

    https://learn.microsoft.com/troubleshoot/windows-server/networking/netsh-advfirewall-firewall-control-firewall-behavior
    https://learn.microsoft.com/powershell/module/netsecurity/new-netfirewallrule

    Args:
        rule_name (str): Display name for the firewall rule.
        app_path (str): Path to the program for which the rule is being created.
        group (str, optional): Group name for the firewall rule (only works with PowerShell).
        direction (str): Direction of the rule (Inbound or Outbound). Default: Inbound.
        profile (str or list, optional): Profile(s) to which the rule should apply (e.g., "Domain,Private"). Default: Any.
        enabled (bool): Specify if the created rule's state is Enabled (True) or not (False). Default: True.
        action (str): Action for the rule (Allow or Block). Default: Allow.
        protocol (str, optional): Protocol by name or number (e.g., "TCP", "UDP", "ICMPv4", or "ICMPv6"). Default: Any.

    Returns:
        waptutils.RunOutput: The result of the command execution.
    """
    if not isinstance(profile, list):
        profile = ensure_list(profile)
    profile = ",".join(profile)

    message = f"Adding Firewall Rule: {rule_name}"
    if direction:
        message += f" ({direction})"
    if protocol:
        message += f" ({protocol})"
    if action:
        message += f" ({action})"
    print(message)
    if windows_version() < WindowsVersions.Windows10:
        direction = "out" if direction.lower() == "Outbound".lower() else "in"
        enabled = "no" if not enabled else "yes"
        cmd_command = f'netsh advfirewall firewall add rule name="{rule_name}" dir={direction} action={action} program="{app_path}" enable={enabled}'
        if profile:  # any and all are working
            cmd_command += f' profile="{profile}"'
        if protocol:
            cmd_command += f' protocol="{protocol}"'
        result = run_notfatal(cmd_command)
    else:
        pwsh_command = (
            f'New-NetFirewallRule -DisplayName "{rule_name}" -Direction {direction} -Action {action} -Program "{app_path}" -Enabled {str(enabled)}'
        )
        if group:
            pwsh_command += f' -Group "{group}"'
        if profile:
            pwsh_command += f' -Profile "{profile}"'
        if protocol:
            pwsh_command += f' -Protocol "{protocol}"'
        result = run_powershell(pwsh_command, output_format="text")

    return result


def remove_netfirewallrule(rule_name):
    """
    Remove Windows Firewall rule using New-NetFirewallRule cmdlet in PowerShell for Windows 10 and newer,
    or netsh advfirewall for older Windows versions.

    Args:
        rule_name (str): Display name of the firewall rule to remove.

    Returns:
        waptutils.RunOutput: The result of the command execution.
    """
    print(f"Removing Firewall Rule: {rule_name}")
    if windows_version() < WindowsVersions.Windows10:
        result = run_notfatal(f'netsh advfirewall firewall delete rule name="{rule_name}"')
    else:
        result = run_powershell(
            f'Remove-NetFirewallRule -DisplayName "{rule_name}" -ErrorAction SilentlyContinue', output_format="text", accept_returncodes=[0, 1, 3010]
        )

    return result
