# 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.

from typing import List
import grpc, logging, uuid
from common.proto.context_pb2 import Connection, Empty, EndPointId
from common.proto.pathcomp_pb2 import PathCompReply, PathCompRequest
from common.proto.pathcomp_pb2_grpc import PathCompServiceServicer
from common.rpc_method_wrapper.Decorator import create_metrics, safe_and_metered_rpc_method
from common.tools.grpc.Tools import grpc_message_to_json, grpc_message_to_json_string
from context.client.ContextClient import ContextClient

LOGGER = logging.getLogger(__name__)

SERVICE_NAME = 'PathComp'
METHOD_NAMES = ['Compute']
METRICS = create_metrics(SERVICE_NAME, METHOD_NAMES)

class PathCompServiceServicerImpl(PathCompServiceServicer):
    def __init__(self) -> None:
        LOGGER.debug('Creating Servicer...')
        LOGGER.debug('Servicer Created')

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def Compute(self, request : PathCompRequest, context : grpc.ServicerContext) -> PathCompReply:
        LOGGER.info('[Compute] begin ; request = {:s}'.format(grpc_message_to_json_string(request)))

        context_client = ContextClient()

        # TODO: consider filtering resources

        grpc_contexts = context_client.ListContexts(Empty())
        grpc_devices = context_client.ListDevices(Empty())
        grpc_links = context_client.ListLinks(Empty())
        for grpc_context in grpc_contexts.contexts:
            # TODO: add context to request
            grpc_topologies = context_client.ListTopologies(grpc_context.context_id)
            for grpc_topology in grpc_topologies.topologies:    #pylint: disable=unused-variable
                # TODO: add topology to request
                pass
        for grpc_device in grpc_devices.devices:                #pylint: disable=unused-variable
            # TODO: add device to request
            pass
        for grpc_link in grpc_links.links:                      #pylint: disable=unused-variable
            # TODO: add link to request
            pass

        reply = PathCompReply()
        # TODO: issue path computation request
        # TODO: compose reply populating reply.services and reply.connections

        for service in request.services:
            # TODO: implement support for multi-point services
            service_endpoint_ids = service.service_endpoint_ids
            if len(service_endpoint_ids) != 2: raise NotImplementedError('Service must have 2 endpoints')
            a_endpoint_id, z_endpoint_id = service_endpoint_ids[0], service_endpoint_ids[-1]

            connection_uuid = str(uuid.uuid4())
            connection_path_hops : List[EndPointId] = []
            connection_path_hops.extend([
                grpc_message_to_json(a_endpoint_id),
                grpc_message_to_json(z_endpoint_id),
            ])
            connection = Connection(**{
                'connection_id': {'connection_uuid': {'uuid': connection_uuid}},
                'service_id': grpc_message_to_json(service.service_id),
                'path_hops_endpoint_ids': connection_path_hops,
                'sub_service_ids': [],
            })
            reply.connections.append(connection)    #pylint: disable=no-member
            reply.services.append(service)          #pylint: disable=no-member

        LOGGER.info('[Compute] end ; reply = {:s}'.format(grpc_message_to_json_string(reply)))
        return reply
