import re
from logging import Logger

from test_automation_suite.utility.cmd import run_cmd


def check_internet_connection(target: str, timeout: int = 30, count: int = 5) -> bool:
    cmd = run_cmd(f"ping {target} -W {timeout} -c {count}")
    return cmd.success


def remove_connection(con: str) -> bool:
    """Remove all connections named "con"

    This ensures creating the connection later in the test does not cause unnecessary errors.
    Because nmcli deletes all connections with this name, no additional logic is required.
    """
    return run_cmd(f"nmcli c delete '{con}'").success


def deactivate_all_connections(logger: Logger) -> bool:
    logger.info("deactivating all connections")
    cmd = run_cmd('nmcli -t | grep " connected"')
    if not cmd.success:
        logger.error("Could not find active connection")
        return False
    for con in cmd.stdout.splitlines():
        if con:
            s = re.search("to\\s.*", con)
            assert s is not None, "regex didn't capture any connection"
            c = s.group()
            c = c[3:]
            # Do not stop execution if this command fails, since the error is often
            # irrelevant. The error is logged anyway, so if it causes issues (e.g.
            # the wired connection was not disconnected and the Wi-Fi test ran
            # incorrectly), this will still be visible in the log file.
            cmd = run_cmd(f'nmcli c down "{c}"')
            if not cmd.success:
                logger.error("Could not disconnect: %s", cmd.stderr)
    return True
