# 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 networkx
from typing import List, Optional
from common.proto.context_pb2 import Device, DeviceId, EndPoint, EndPointId, LinkId
from .Enums import EdgeTypeEnum

def get_device_key(device_id : DeviceId) -> str:
    return device_id.device_uuid.uuid # pylint: disable=no-member

def get_endpoint_key(endpoint_id : EndPointId, device_uuid : Optional[str] = None) -> str:
    if device_uuid is None: device_uuid = endpoint_id.device_id.device_uuid.uuid # pylint: disable=no-member
    endpoint_uuid = endpoint_id.endpoint_uuid.uuid # pylint: disable=no-member
    return '{:s}/{:s}'.format(device_uuid, endpoint_uuid)

def get_link_key(link_id : LinkId) -> str:
    return link_id.link_uuid.uuid # pylint: disable=no-member

def get_device(topology : networkx.Graph, device_key : str) -> Device:
    return topology.nodes[device_key]['device']

def get_endpoint(topology : networkx.Graph, endpoint_key : str) -> EndPoint:
    return topology.nodes[endpoint_key]['endpoint']

def get_edge_type(topology : networkx.Graph, endpoint_keys : List[str]) -> EdgeTypeEnum:
    # pylint: disable=no-member,protected-access
    endpoint_types = {get_endpoint(topology, endpoint_key).endpoint_type for endpoint_key in endpoint_keys}
    edge_type = None if len(endpoint_types) > 1 else \
        EdgeTypeEnum._value2member_map_.get(endpoint_types.pop())
    if edge_type is None: edge_type = EdgeTypeEnum.OTHER
    return edge_type
