# 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 grpc, json, logging, requests, uuid
from typing import List
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
from pathcomp.frontend.Config import BACKEND_HOST, BACKEND_PORT, BACKEND_URL
from pathcomp.frontend.service.tools.ComposeRequest import compose_device, compose_link, compose_service

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)))

        algorithm = request.WhichOneof('algorithm')
        if algorithm == 'shortest_path':
            # no attributes
            pass
        elif algorithm == 'k_shortest_path':
            k_inspection = request.k_shortest_path.k_inspection
            k_return = request.k_shortest_path.k_return
        else:
            raise NotImplementedError('Unsupported Algorithm: {:s}'.format(str(algorithm)))

        context_client = ContextClient()

        algorithm = {'id': 'KSP', 'sync': False, 'k_paths': k_return}
        service_list = [
            compose_service(grpc_service, algorithm)
            for grpc_service in request.services
        ]

        # TODO: consider filtering resources

        #grpc_contexts = context_client.ListContexts(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

        grpc_devices = context_client.ListDevices(Empty())
        device_list = [
            compose_device(grpc_device)
            for grpc_device in grpc_devices.devices
        ]

        grpc_links = context_client.ListLinks(Empty())
        link_list = [
            compose_link(grpc_link)
            for grpc_link in grpc_links.links
        ]

        request = {
            'serviceList': service_list,
            'deviceList' : device_list,
            'linkList'   : link_list,
        }

        backend_url = BACKEND_URL.format(BACKEND_HOST, BACKEND_PORT)
        reply = requests.post(backend_url, json=request)
        if reply.status_code not in {requests.codes.ok}:
            raise Exception('Backend error({:s}) for request({:s})'.format(
                str(reply.content.decode('UTF-8')), json.dumps(request, sort_keys=True)))
        LOGGER.info('status_code={:s} reply={:s}'.format(
            str(reply.status_code), str(reply.content.decode('UTF-8'))))



        reply = PathCompReply()
        # 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