import logging, lxml.etree as ET
from typing import Any, Dict, List, Tuple
from .Namespace import NAMESPACES
from .Tools import add_value_from_collection, add_value_from_tag

LOGGER = logging.getLogger(__name__)

XPATH_NETWORK_INSTANCES = "//ocni:network-instances/ocni:network-instance"

def parse(xml_data : ET.Element) -> List[Tuple[str, Dict[str, Any]]]:
    response = []
    for xml_network_instance in xml_data.xpath(XPATH_NETWORK_INSTANCES, namespaces=NAMESPACES):
        #LOGGER.info('xml_network_instance = {:s}'.format(str(ET.tostring(xml_network_instance))))

        network_instance = {}

        ni_name = xml_network_instance.find('ocni:name', namespaces=NAMESPACES)
        if ni_name is None or ni_name.text is None: continue
        add_value_from_tag(network_instance, 'name', ni_name)

        ni_type = xml_network_instance.find('ocni:config/ocni:type', namespaces=NAMESPACES)
        add_value_from_tag(network_instance, 'type', ni_type)

        ni_router_id = xml_network_instance.find('ocni:config/ocni:router-id', namespaces=NAMESPACES)
        add_value_from_tag(network_instance, 'router_id', ni_router_id)

        ni_route_dist = xml_network_instance.find('ocni:config/ocni:route-distinguisher', namespaces=NAMESPACES)
        add_value_from_tag(network_instance, 'route_distinguisher', ni_route_dist)

        ni_address_families = []
        add_value_from_collection(network_instance, 'address_families', ni_address_families)

        if len(network_instance) == 0: continue
        response.append(('network_instance[{:s}]'.format(network_instance['name']), network_instance))
    return response
