# 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, Tuple
from common.proto.kpi_sample_types_pb2 import KpiSampleType
from device.service.driver_api._Driver import RESOURCE_ENDPOINTS
from .Constants import SPECIAL_RESOURCE_MAPPINGS

LOGGER = logging.getLogger(__name__)

def compose_resource_endpoint(endpoint_data : Dict[str, Any]) -> Tuple[str, Any]:
    endpoint_uuid = endpoint_data.get('uuid')
    if endpoint_uuid is None: return None
    endpoint_resource_path = SPECIAL_RESOURCE_MAPPINGS.get(RESOURCE_ENDPOINTS)
    endpoint_resource_key = '{:s}/endpoint[{:s}]'.format(endpoint_resource_path, endpoint_uuid)

    endpoint_type = endpoint_data.get('type')
    if endpoint_type is None: return None

    endpoint_sample_types = endpoint_data.get('sample_types')
    if endpoint_sample_types is None: return None

    sample_types = {}
    for endpoint_sample_type in endpoint_sample_types:
        try:
            metric_name = KpiSampleType.Name(endpoint_sample_type).lower().replace('kpisampletype_', '')
        except: # pylint: disable=bare-except
            LOGGER.warning('Unsupported EndPointSampleType({:s})'.format(str(endpoint_sample_type)))
            continue
        monitoring_resource_key = '{:s}/state/{:s}'.format(endpoint_resource_key, metric_name)
        sample_types[endpoint_sample_type] = monitoring_resource_key

    endpoint_resource_value = {'uuid': endpoint_uuid, 'type': endpoint_type, 'sample_types': sample_types}
    return endpoint_resource_key, endpoint_resource_value
