import subprocess
from os import linesep


def get_wifi_networks():
    command = 'nmcli -t -f ssid,signal,security device wifi list'
    output = subprocess.check_output([command], shell=True)
    networks_infos = output.decode('utf-8').split(linesep)
    parsed_infos = []
    for network_info in networks_infos:
        splits = network_info.split(':')
        if len(splits) <= 1:
            continue
        ssid = splits[0]
        # duplicate
        if ssid in [network['ssid'] for network in parsed_infos]:
            continue
        secured = bool(splits[2])
        parsed_infos.append(
            {'ssid': splits[0], 'signal': int(splits[1]), 'secured': secured}
        )
    return parsed_infos


def connect(ssid, password):
    cli = "nmcli device wifi connect '{}'".format(ssid)
    if password:
        cli += " password '{}'".format(password)
    try:
        output = subprocess.check_output([cli], shell=True).decode('utf-8')
        if ('successfully activated' in output):
            return (True, output)
        else:
            return (False, output)
    except subprocess.CalledProcessError as e:
        return (False, e)
