# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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
from typing import Any, Dict, List, Tuple
from common.proto.kpi_sample_types_pb2 import KpiSampleType
from ._Handler import _Handler

LOGGER = logging.getLogger(__name__)

PATH_IF_CTR = "/interfaces/interface[name={:s}]/state/counters/{:s}"

class ComponentHandler(_Handler):
    def get_resource_key(self) -> str: return '/endpoints/endpoint'
    def get_path(self) -> str: return '/components/component'

    def parse(self, json_data : Dict) -> List[Tuple[str, Dict[str, Any]]]:
        #LOGGER.info('json_data = {:s}'.format(json.dumps(json_data)))
        json_component_list : List[Dict] = json_data.get('component', [])
        response = []
        for json_component in json_component_list:
            #LOGGER.info('json_component = {:s}'.format(json.dumps(json_component)))

            endpoint = {}

            component_type = json_component.get('state', {}).get('type')
            if component_type is None: continue
            component_type = component_type.replace('oc-platform-types:', '')
            component_type = component_type.replace('openconfig-platform-types:', '')
            if component_type not in {'PORT'}: continue
            endpoint['type'] = '-'

            #LOGGER.info('PORT json_component = {:s}'.format(json.dumps(json_component)))

            component_name = json_component.get('name')
            if component_name is None: continue

            # TODO: improve mapping between interface name and component name
            # By now, computed by time for the sake of saving time for the Hackfest.
            interface_name = component_name.lower().replace('-port', '')

            endpoint['uuid'] = interface_name
            endpoint['sample_types'] = {
                KpiSampleType.KPISAMPLETYPE_BYTES_RECEIVED     : PATH_IF_CTR.format(interface_name, 'in-octets' ),
                KpiSampleType.KPISAMPLETYPE_BYTES_TRANSMITTED  : PATH_IF_CTR.format(interface_name, 'out-octets'),
                KpiSampleType.KPISAMPLETYPE_PACKETS_RECEIVED   : PATH_IF_CTR.format(interface_name, 'in-pkts'   ),
                KpiSampleType.KPISAMPLETYPE_PACKETS_TRANSMITTED: PATH_IF_CTR.format(interface_name, 'out-pkts'  ),
            }

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