import logging, lxml.etree as ET
from typing import Any, Dict, List, Tuple
from device.service.database.KpiSampleType import ORM_KpiSampleTypeEnum
from .Namespace import NAMESPACES
from .Tools import add_value_from_collection, add_value_from_tag

LOGGER = logging.getLogger(__name__)

XPATH_PORTS = "//ocp:components/ocp:component/ocp:state[ocp:type='PORT']/.."
XPATH_IFACE_COUNTER = "//oci:interfaces/oci:interface[oci:name='{:s}']/state/counters/{:s}"

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)

        sample_types = {
            ORM_KpiSampleTypeEnum.BYTES_RECEIVED.value     : XPATH_IFACE_COUNTER.format(endpoint['uuid'], 'in-octets' ),
            ORM_KpiSampleTypeEnum.BYTES_TRANSMITTED.value  : XPATH_IFACE_COUNTER.format(endpoint['uuid'], 'out-octets'),
            ORM_KpiSampleTypeEnum.PACKETS_RECEIVED.value   : XPATH_IFACE_COUNTER.format(endpoint['uuid'], 'in-pkts'   ),
            ORM_KpiSampleTypeEnum.PACKETS_TRANSMITTED.value: XPATH_IFACE_COUNTER.format(endpoint['uuid'], 'out-pkts'  ),
        }
        add_value_from_collection(endpoint, 'sample_types', sample_types)

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