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

LOGGER = logging.getLogger(__name__)

XPATH_PORTS = "//ocp:components/ocp:component/ocp:state[ocp:type='PORT']/.."

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

        endpoint = {}

        component_name = xml_component.find('ocp:name', namespaces=NAMESPACES)
        if component_name is None or component_name.text is None: continue
        add_value_from_tag(endpoint, 'uuid', component_name)

        component_type = xml_component.find(
            'ocpp:port/ocpp:breakout-mode/ocpp:state/ocpp:channel-speed', namespaces=NAMESPACES)
        add_value_from_tag(endpoint, 'type', component_type)

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