"""
Module for configuring Windows Firewall using ``netsh``
"""

import re

import salt.utils.platform
import salt.utils.win_lgpo_netsh
from salt.exceptions import CommandExecutionError

# Define the module's virtual name
__virtualname__ = "firewall"


def __virtual__():
    """
    Only works on Windows systems
    """
    if not salt.utils.platform.is_windows():
        return False, "Module win_firewall: module only available on Windows"

    return __virtualname__


def get_config():
    """
    Get the status of all the firewall profiles

    Returns:
        dict: A dictionary of all profiles on the system

    Raises:
        CommandExecutionError: If the command fails

    CLI Example:

    .. code-block:: bash

        salt '*' firewall.get_config
    """
    profiles = {}
    curr = None

    cmd = ["netsh", "advfirewall", "show", "allprofiles"]
    ret = __salt__["cmd.run_all"](cmd, python_shell=False, ignore_retcode=True)
    if ret["retcode"] != 0:
        raise CommandExecutionError(ret["stdout"])

    # There may be some problems with this depending on how `netsh` is localized
    # It's looking for lines that contain `Profile Settings` or start with
    # `State` which may be different in different localizations
    for line in ret["stdout"].splitlines():
        if not curr:
            tmp = re.search("(.*) Profile Settings:", line)
            if tmp:
                curr = tmp.group(1)
        elif line.startswith("State"):
            profiles[curr] = line.split()[1] == "ON"
            curr = None

    return profiles


def disable(profile="allprofiles"):
    """
    Disable firewall profile

    Args:
        profile (Optional[str]): The name of the profile to disable. Default is
            ``allprofiles``. Valid options are:

            - allprofiles
            - domainprofile
            - privateprofile
            - publicprofile

    Returns:
        bool: True if successful

    Raises:
        CommandExecutionError: If the command fails

    CLI Example:

    .. code-block:: bash

        salt '*' firewall.disable