from __future__ import absolute_import
from __future__ import division
from functools import partial
from glob import iglob
import logging
import os

from vdsm.network.ipwrapper import Link
from .misc import visible_devs

BRIDGING_OPT = '/sys/class/net/%s/bridge/%s'

bridges = partial(visible_devs, Link.isBRIDGE)


def ports(bridge):
    brif_path = os.path.join('/sys/class/net', bridge, 'brif')
    if os.path.isdir(brif_path):
        bridge_ports = os.listdir(brif_path)
    else:
        logging.warning('%s is not a Linux bridge', bridge)
        bridge_ports = []
    return bridge_ports


def bridge_options(bridge):
    BR_KEY_BLACKLIST = ('flush',)
    paths = iglob(BRIDGING_OPT % (bridge, '*'))
    opts = {}
    for path in paths:
        key = os.path.basename(path)
        if key in BR_KEY_BLACKLIST:
            continue
        with open(path) as optFile:
            opts[key] = optFile.read().rstrip()
    return opts


def stp_state(bridge):
    with open(BRIDGING_OPT % (bridge, 'stp_state')) as stp_file:
        stp = stp_file.readline()
    if stp == '1\n':
        return 'on'
    else:
        return 'off'


def stp_booleanize(value):
    if value is None:
        return False
    if type(value) is bool:
        return value
    if value.lower() in ('true', 'on', 'yes'):
        return True
    elif value.lower() in ('false', 'off', 'no'):
        return False
    else:
        raise ValueError('Invalid value for bridge stp')


def info(link):
    return {'ports': ports(link.name),
            'stp': stp_state(link.name)}
