# 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.Constants import DEFAULT_CONTEXT_UUID
from common.DeviceTypes import DeviceTypeEnum
from common.proto.context_pb2 import ContextId, Empty, ServiceTypeEnum
from common.tools.descriptor.Loader import DescriptorLoader
from common.tools.object_factory.Context import json_context_id
from common.tools.grpc.Tools import grpc_message_to_json_string
from context.client.ContextClient import ContextClient
from tests.Fixtures import context_client   # pylint: disable=unused-import
from tests.tools.mock_osm.MockOSM import MockOSM
from .Fixtures import osm_wim # pylint: disable=unused-import


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

DEVTYPE_EMU_PR  = DeviceTypeEnum.EMULATED_PACKET_ROUTER.value
DEVTYPE_EMU_OLS = DeviceTypeEnum.EMULATED_OPEN_LINE_SYSTEM.value

DESCRIPTOR_FILE = 'ofc22/descriptors_emulated.json'


def test_service_removal(context_client : ContextClient, osm_wim : MockOSM): # pylint: disable=redefined-outer-name
    # ----- List entities - Ensure service is created ------------------------------------------------------------------
    with open(DESCRIPTOR_FILE, 'r', encoding='UTF-8') as f:
        descriptors = f.read()

    descriptor_loader = DescriptorLoader(descriptors)

    response = context_client.ListContexts(Empty())
    assert len(response.contexts) == descriptor_loader.num_contexts

    for context_uuid, num_topologies in descriptor_loader.num_topologies.items():
        response = context_client.ListTopologies(ContextId(**json_context_id(context_uuid)))
        assert len(response.topologies) == num_topologies

    response = context_client.ListDevices(Empty())
    assert len(response.devices) == descriptor_loader.num_devices

    response = context_client.ListLinks(Empty())
    assert len(response.links) == descriptor_loader.num_links

    l3nm_service_uuids = set()
    response = context_client.ListServices(ContextId(**json_context_id(DEFAULT_CONTEXT_UUID)))
    assert len(response.services) == 2 # OLS & L3NM => (L3NM + TAPI)
    for service in response.services:
        service_id = service.service_id

        if service.service_type == ServiceTypeEnum.SERVICETYPE_L3NM:
            service_uuid = service_id.service_uuid.uuid
            l3nm_service_uuids.add(service_uuid)
            osm_wim.conn_info[service_uuid] = {}

        response = context_client.ListConnections(service_id)
        LOGGER.info('  ServiceId[{:s}] => Connections[{:d}] = {:s}'.format(
            grpc_message_to_json_string(service_id), len(response.connections),
            grpc_message_to_json_string(response)))
        assert len(response.connections) == 1 # one connection per service

    # Identify service to delete
    assert len(l3nm_service_uuids) == 1  # assume a single L3NM service has been created
    l3nm_service_uuid = set(l3nm_service_uuids).pop()


    # ----- Delete Service ---------------------------------------------------------------------------------------------
    osm_wim.delete_connectivity_service(l3nm_service_uuid)


    # ----- List entities - Ensure service is removed ------------------------------------------------------------------
    response = context_client.ListContexts(Empty())
    assert len(response.contexts) == descriptor_loader.num_contexts

    for context_uuid, num_topologies in descriptor_loader.num_topologies.items():
        response = context_client.ListTopologies(ContextId(**json_context_id(context_uuid)))
        assert len(response.topologies) == num_topologies

    response = context_client.ListDevices(Empty())
    assert len(response.devices) == descriptor_loader.num_devices

    response = context_client.ListLinks(Empty())
    assert len(response.links) == descriptor_loader.num_links

    for context_uuid, num_services in descriptor_loader.num_services.items():
        response = context_client.ListServices(ContextId(**json_context_id(context_uuid)))
        assert len(response.services) == 0
