# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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
