# 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 logging
from common.proto.context_pb2 import Context, ContextId, DeviceId, Link, LinkId, Topology, Device, TopologyId
from common.proto.pathcomp_pb2 import PathCompRequest
from common.tools.grpc.Tools import grpc_message_to_json
from context.client.ContextClient import ContextClient
from device.client.DeviceClient import DeviceClient
from pathcomp.frontend.client.PathCompClient import PathCompClient
from .Objects import CONTEXTS, DEVICES, LINKS, SERVICES, TOPOLOGIES
from .PrepareTestScenario import ( # pylint: disable=unused-import
    # be careful, order of symbols is important here!
    mock_service, pathcomp_service, context_client, device_client, pathcomp_client)

LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)


def test_prepare_environment(
    context_client : ContextClient, # pylint: disable=redefined-outer-name
    device_client : DeviceClient):  # pylint: disable=redefined-outer-name

    for context  in CONTEXTS  : context_client.SetContext (Context (**context ))
    for topology in TOPOLOGIES: context_client.SetTopology(Topology(**topology))
    for device   in DEVICES   : device_client .AddDevice  (Device  (**device  ))
    for link     in LINKS     : context_client.SetLink    (Link    (**link    ))


def test_request_service(
    pathcomp_client : PathCompClient):  # pylint: disable=redefined-outer-name

    request_services = SERVICES
    pathcomp_request = PathCompRequest(services=request_services)
    pathcomp_reply = pathcomp_client.Compute(pathcomp_request)
    pathcomp_reply = grpc_message_to_json(pathcomp_reply)
    reply_services = pathcomp_reply['services']
    reply_connections = pathcomp_reply['connections']
    assert len(request_services) <= len(reply_services)
    request_service_ids = {
        '{:s}/{:s}'.format(
            svc['service_id']['context_id']['context_uuid']['uuid'],
            svc['service_id']['service_uuid']['uuid']
        )
        for svc in request_services
    }
    reply_service_ids = {
        '{:s}/{:s}'.format(
            svc['service_id']['context_id']['context_uuid']['uuid'],
            svc['service_id']['service_uuid']['uuid']
        )
        for svc in reply_services
    }
    # Assert all requested services have a reply
    # It permits having other services not requested (i.e., sub-services)
    assert len(request_service_ids.difference(reply_service_ids)) == 0

    reply_connection_service_ids = {
        '{:s}/{:s}'.format(
            conn['service_id']['context_id']['context_uuid']['uuid'],
            conn['service_id']['service_uuid']['uuid']
        )
        for conn in reply_connections
    }
    # Assert all requested services have a connection associated
    # It permits having other connections not requested (i.e., connections for sub-services)
    assert len(request_service_ids.difference(reply_connection_service_ids)) == 0

    # TODO: implement other checks. examples:
    # - request service and reply service endpoints match
    # - request service and reply connection endpoints match
    # - reply sub-service and reply sub-connection endpoints match
    # - others?
    #for json_service,json_connection in zip(json_services, json_connections):


def test_cleanup_environment(
    context_client : ContextClient, # pylint: disable=redefined-outer-name
    device_client : DeviceClient):  # pylint: disable=redefined-outer-name

    for link     in LINKS     : context_client.RemoveLink    (LinkId    (**link    ['link_id'    ]))
    for device   in DEVICES   : device_client .DeleteDevice  (DeviceId  (**device  ['device_id'  ]))
    for topology in TOPOLOGIES: context_client.RemoveTopology(TopologyId(**topology['topology_id']))
    for context  in CONTEXTS  : context_client.RemoveContext (ContextId (**context ['context_id' ]))
