# 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 copy, grpc, pytest
from typing import Tuple
from common.Constants import DEFAULT_CONTEXT_UUID, DEFAULT_TOPOLOGY_UUID
from common.proto.context_pb2 import (
    Connection, ConnectionEvent, ConnectionId, Context, ContextEvent, ContextId, Device, DeviceEvent, DeviceId,
    EventTypeEnum, Service, ServiceEvent, ServiceId, Topology, TopologyEvent, TopologyId)
from context.client.ContextClient import ContextClient
from context.client.EventsCollector import EventsCollector
from .Objects import (
    CONNECTION_R1_R3, CONNECTION_R1_R3_ID, CONNECTION_R1_R3_UUID, CONTEXT, CONTEXT_ID, DEVICE_R1, DEVICE_R1_ID,
    DEVICE_R1_UUID, DEVICE_R2, DEVICE_R2_ID, DEVICE_R2_UUID, DEVICE_R3, DEVICE_R3_ID, DEVICE_R3_UUID, SERVICE_R1_R2,
    SERVICE_R1_R2_ID, SERVICE_R1_R2_UUID, SERVICE_R1_R3, SERVICE_R1_R3_ID, SERVICE_R1_R3_UUID, SERVICE_R2_R3,
    SERVICE_R2_R3_ID, SERVICE_R2_R3_UUID, TOPOLOGY, TOPOLOGY_ID)

def grpc_connection(
    context_client_grpc : ContextClient,                # pylint: disable=redefined-outer-name
    context_db_mb : Tuple[Database, MessageBroker]):    # pylint: disable=redefined-outer-name
    Session = context_db_mb[0]

    database = Database(Session)

    # ----- Clean the database -----------------------------------------------------------------------------------------
    database.clear()

    # ----- Initialize the EventsCollector -----------------------------------------------------------------------------
    events_collector = EventsCollector(context_client_grpc)
    events_collector.start()

    # ----- Prepare dependencies for the test and capture related events -----------------------------------------------
    response = context_client_grpc.SetContext(Context(**CONTEXT))
    assert response.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    response = context_client_grpc.SetTopology(Topology(**TOPOLOGY))
    assert response.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert response.topology_uuid.uuid == DEFAULT_TOPOLOGY_UUID

    response = context_client_grpc.SetDevice(Device(**DEVICE_R1))
    assert response.device_uuid.uuid == DEVICE_R1_UUID

    response = context_client_grpc.SetDevice(Device(**DEVICE_R2))
    assert response.device_uuid.uuid == DEVICE_R2_UUID

    response = context_client_grpc.SetDevice(Device(**DEVICE_R3))
    assert response.device_uuid.uuid == DEVICE_R3_UUID

    response = context_client_grpc.SetService(Service(**SERVICE_R1_R2))
    assert response.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert response.service_uuid.uuid == SERVICE_R1_R2_UUID

    CONTEXT_WITH_SERVICE = copy.deepcopy(CONTEXT)
    CONTEXT_WITH_SERVICE['service_ids'].append(SERVICE_R1_R2_ID)
    response = context_client_grpc.SetContext(Context(**CONTEXT_WITH_SERVICE))
    assert response.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    response = context_client_grpc.SetService(Service(**SERVICE_R2_R3))
    assert response.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert response.service_uuid.uuid == SERVICE_R2_R3_UUID

    CONTEXT_WITH_SERVICE = copy.deepcopy(CONTEXT)
    CONTEXT_WITH_SERVICE['service_ids'].append(SERVICE_R2_R3_ID)
    response = context_client_grpc.SetContext(Context(**CONTEXT_WITH_SERVICE))
    assert response.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    response = context_client_grpc.SetService(Service(**SERVICE_R1_R3))
    assert response.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert response.service_uuid.uuid == SERVICE_R1_R3_UUID

    CONTEXT_WITH_SERVICE = copy.deepcopy(CONTEXT)
    CONTEXT_WITH_SERVICE['service_ids'].append(SERVICE_R1_R3_ID)
    response = context_client_grpc.SetContext(Context(**CONTEXT_WITH_SERVICE))
    assert response.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    events = events_collector.get_events(block=True, count=11)

    assert isinstance(events[0], ContextEvent)
    assert events[0].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[0].context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    assert isinstance(events[1], TopologyEvent)
    assert events[1].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[1].topology_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[1].topology_id.topology_uuid.uuid == DEFAULT_TOPOLOGY_UUID

    assert isinstance(events[2], DeviceEvent)
    assert events[2].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[2].device_id.device_uuid.uuid == DEVICE_R1_UUID

    assert isinstance(events[3], DeviceEvent)
    assert events[3].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[3].device_id.device_uuid.uuid == DEVICE_R2_UUID

    assert isinstance(events[4], DeviceEvent)
    assert events[4].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[4].device_id.device_uuid.uuid == DEVICE_R3_UUID

    assert isinstance(events[5], ServiceEvent)
    assert events[5].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[5].service_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[5].service_id.service_uuid.uuid == SERVICE_R1_R2_UUID

    assert isinstance(events[6], ContextEvent)
    assert events[6].event.event_type == EventTypeEnum.EVENTTYPE_UPDATE
    assert events[6].context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    assert isinstance(events[7], ServiceEvent)
    assert events[7].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[7].service_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[7].service_id.service_uuid.uuid == SERVICE_R2_R3_UUID

    assert isinstance(events[8], ContextEvent)
    assert events[8].event.event_type == EventTypeEnum.EVENTTYPE_UPDATE
    assert events[8].context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    assert isinstance(events[9], ServiceEvent)
    assert events[9].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert events[9].service_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[9].service_id.service_uuid.uuid == SERVICE_R1_R3_UUID

    assert isinstance(events[10], ContextEvent)
    assert events[10].event.event_type == EventTypeEnum.EVENTTYPE_UPDATE
    assert events[10].context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    # ----- Get when the object does not exist -------------------------------------------------------------------------
    with pytest.raises(grpc.RpcError) as e:
        context_client_grpc.GetConnection(ConnectionId(**CONNECTION_R1_R3_ID))
    assert e.value.code() == grpc.StatusCode.NOT_FOUND
    assert e.value.details() == 'Connection({:s}) not found'.format(CONNECTION_R1_R3_UUID)

    # ----- List when the object does not exist ------------------------------------------------------------------------
    response = context_client_grpc.ListConnectionIds(ServiceId(**SERVICE_R1_R3_ID))
    assert len(response.connection_ids) == 0

    response = context_client_grpc.ListConnections(ServiceId(**SERVICE_R1_R3_ID))
    assert len(response.connections) == 0

    # ----- Dump state of database before create the object ------------------------------------------------------------
    db_entries = context_database.dump()
    LOGGER.info('----- Database Dump [{:3d} entries] -------------------------'.format(len(db_entries)))
    for db_entry in db_entries:
        LOGGER.info('  [{:>4s}] {:40s} :: {:s}'.format(*db_entry)) # pragma: no cover
    LOGGER.info('-----------------------------------------------------------')
    assert len(db_entries) == 187

    # ----- Create the object ------------------------------------------------------------------------------------------
    with pytest.raises(grpc.RpcError) as e:
        WRONG_CONNECTION = copy.deepcopy(CONNECTION_R1_R3)
        WRONG_CONNECTION['path_hops_endpoint_ids'][0]\
            ['topology_id']['context_id']['context_uuid']['uuid'] = 'wrong-context-uuid'
        context_client_grpc.SetConnection(Connection(**WRONG_CONNECTION))
    assert e.value.code() == grpc.StatusCode.NOT_FOUND
    # TODO: should we check that all endpoints belong to same topology?
    # TODO: should we check that endpoints form links over the topology?
    msg = 'EndPoint({:s}/{:s}:wrong-context-uuid/{:s}) not found'.format(
        DEVICE_R1_UUID, WRONG_CONNECTION['path_hops_endpoint_ids'][0]['endpoint_uuid']['uuid'], DEFAULT_TOPOLOGY_UUID)
    assert e.value.details() == msg

    response = context_client_grpc.SetConnection(Connection(**CONNECTION_R1_R3))
    assert response.connection_uuid.uuid == CONNECTION_R1_R3_UUID

    # ----- Check create event -----------------------------------------------------------------------------------------
    event = events_collector.get_event(block=True)
    assert isinstance(event, ConnectionEvent)
    assert event.event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    assert event.connection_id.connection_uuid.uuid == CONNECTION_R1_R3_UUID

    # ----- Update the object ------------------------------------------------------------------------------------------
    response = context_client_grpc.SetConnection(Connection(**CONNECTION_R1_R3))
    assert response.connection_uuid.uuid == CONNECTION_R1_R3_UUID

    # ----- Check update event -----------------------------------------------------------------------------------------
    event = events_collector.get_event(block=True)
    assert isinstance(event, ConnectionEvent)
    assert event.event.event_type == EventTypeEnum.EVENTTYPE_UPDATE
    assert event.connection_id.connection_uuid.uuid == CONNECTION_R1_R3_UUID

    # ----- Dump state of database after create/update the object ------------------------------------------------------
    db_entries = context_database.dump()
    LOGGER.info('----- Database Dump [{:3d} entries] -------------------------'.format(len(db_entries)))
    for db_entry in db_entries:
        LOGGER.info('  [{:>4s}] {:40s} :: {:s}'.format(*db_entry)) # pragma: no cover
    LOGGER.info('-----------------------------------------------------------')
    assert len(db_entries) == 203

    # ----- Get when the object exists ---------------------------------------------------------------------------------
    response = context_client_grpc.GetConnection(ConnectionId(**CONNECTION_R1_R3_ID))
    assert response.connection_id.connection_uuid.uuid == CONNECTION_R1_R3_UUID
    assert response.service_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert response.service_id.service_uuid.uuid == SERVICE_R1_R3_UUID
    assert len(response.path_hops_endpoint_ids) == 6
    assert len(response.sub_service_ids) == 2

    # ----- List when the object exists --------------------------------------------------------------------------------
    response = context_client_grpc.ListConnectionIds(ServiceId(**SERVICE_R1_R3_ID))
    assert len(response.connection_ids) == 1
    assert response.connection_ids[0].connection_uuid.uuid == CONNECTION_R1_R3_UUID

    response = context_client_grpc.ListConnections(ServiceId(**SERVICE_R1_R3_ID))
    assert len(response.connections) == 1
    assert response.connections[0].connection_id.connection_uuid.uuid == CONNECTION_R1_R3_UUID
    assert len(response.connections[0].path_hops_endpoint_ids) == 6
    assert len(response.connections[0].sub_service_ids) == 2

    # ----- Remove the object ------------------------------------------------------------------------------------------
    context_client_grpc.RemoveConnection(ConnectionId(**CONNECTION_R1_R3_ID))
    context_client_grpc.RemoveService(ServiceId(**SERVICE_R1_R3_ID))
    context_client_grpc.RemoveService(ServiceId(**SERVICE_R2_R3_ID))
    context_client_grpc.RemoveService(ServiceId(**SERVICE_R1_R2_ID))
    context_client_grpc.RemoveDevice(DeviceId(**DEVICE_R1_ID))
    context_client_grpc.RemoveDevice(DeviceId(**DEVICE_R2_ID))
    context_client_grpc.RemoveDevice(DeviceId(**DEVICE_R3_ID))
    context_client_grpc.RemoveTopology(TopologyId(**TOPOLOGY_ID))
    context_client_grpc.RemoveContext(ContextId(**CONTEXT_ID))

    # ----- Check remove event -----------------------------------------------------------------------------------------
    events = events_collector.get_events(block=True, count=9)

    assert isinstance(events[0], ConnectionEvent)
    assert events[0].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[0].connection_id.connection_uuid.uuid == CONNECTION_R1_R3_UUID

    assert isinstance(events[1], ServiceEvent)
    assert events[1].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[1].service_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[1].service_id.service_uuid.uuid == SERVICE_R1_R3_UUID

    assert isinstance(events[2], ServiceEvent)
    assert events[2].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[2].service_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[2].service_id.service_uuid.uuid == SERVICE_R2_R3_UUID

    assert isinstance(events[3], ServiceEvent)
    assert events[3].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[3].service_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[3].service_id.service_uuid.uuid == SERVICE_R1_R2_UUID

    assert isinstance(events[4], DeviceEvent)
    assert events[4].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[4].device_id.device_uuid.uuid == DEVICE_R1_UUID

    assert isinstance(events[5], DeviceEvent)
    assert events[5].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[5].device_id.device_uuid.uuid == DEVICE_R2_UUID

    assert isinstance(events[6], DeviceEvent)
    assert events[6].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[6].device_id.device_uuid.uuid == DEVICE_R3_UUID

    assert isinstance(events[7], TopologyEvent)
    assert events[7].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[7].topology_id.context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID
    assert events[7].topology_id.topology_uuid.uuid == DEFAULT_TOPOLOGY_UUID

    assert isinstance(events[8], ContextEvent)
    assert events[8].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    assert events[8].context_id.context_uuid.uuid == DEFAULT_CONTEXT_UUID

    # ----- Stop the EventsCollector -----------------------------------------------------------------------------------
    events_collector.stop()

    # ----- Dump state of database after remove the object -------------------------------------------------------------
    db_entries = context_database.dump()
    LOGGER.info('----- Database Dump [{:3d} entries] -------------------------'.format(len(db_entries)))
    for db_entry in db_entries:
        LOGGER.info('  [{:>4s}] {:40s} :: {:s}'.format(*db_entry)) # pragma: no cover
    LOGGER.info('-----------------------------------------------------------')
    assert len(db_entries) == 0
