import json, logging
from typing import Dict, List, Tuple
from common.tools.grpc.Tools import grpc_message_to_json_string
from context.client.EventsCollector import EventsCollector
from context.proto.context_pb2 import (
    ConnectionEvent, ContextEvent, DeviceEvent, EventTypeEnum, LinkEvent, ServiceEvent, TopologyEvent)

LOGGER = logging.getLogger(__name__)

EVENT_CREATE = EventTypeEnum.EVENTTYPE_CREATE
EVENT_UPDATE = EventTypeEnum.EVENTTYPE_UPDATE
EVENT_REMOVE = EventTypeEnum.EVENTTYPE_REMOVE

def class_to_classname(klass): return klass.__name__
def instance_to_classname(instance): return type(instance).__name__

CLASSNAME_CONTEXT_EVENT    = class_to_classname(ContextEvent)
CLASSNAME_TOPOLOGY_EVENT   = class_to_classname(TopologyEvent)
CLASSNAME_DEVICE_EVENT     = class_to_classname(DeviceEvent)
CLASSNAME_LINK_EVENT       = class_to_classname(LinkEvent)
CLASSNAME_SERVICE_EVENT    = class_to_classname(ServiceEvent)
CLASSNAME_CONNECTION_EVENT = class_to_classname(ConnectionEvent)

EVENT_CLASS_NAME__TO__ENTITY_ID_SELECTOR = {
    CLASSNAME_CONTEXT_EVENT   : lambda event: event.context_id,
    CLASSNAME_TOPOLOGY_EVENT  : lambda event: event.topology_id,
    CLASSNAME_DEVICE_EVENT    : lambda event: event.device_id,
    CLASSNAME_LINK_EVENT      : lambda event: event.link_id,
    CLASSNAME_SERVICE_EVENT   : lambda event: event.service_id,
    CLASSNAME_CONNECTION_EVENT: lambda event: event.connection_id,
}

def event_to_key(event):
    event_class_name = instance_to_classname(event)
    entity_id_selector_function = EVENT_CLASS_NAME__TO__ENTITY_ID_SELECTOR.get(event_class_name)
    entity_id = entity_id_selector_function(event)
    return (event_class_name, event.event.event_type, grpc_message_to_json_string(entity_id))

def check_events(events_collector : EventsCollector, expected_events : List[Tuple[str, int, Dict]]):
    expected_events_map = {}
    num_events_expected = 0
    for event_classname, event_type_id, event_ids in expected_events:
        event_key = (event_classname, event_type_id, json.dumps(event_ids, sort_keys=True))
        event_count = expected_events_map.get(event_key, 0)
        expected_events_map[event_key] = event_count + 1
        num_events_expected += 1

    events_received = events_collector.get_events(block=True, count=num_events_expected)
    for i, event_received in enumerate(events_received):
        LOGGER.info('event_received[{:d}] = {:s}'.format(i, str(event_received)))
        event_key = event_to_key(event_received)
        event_count = expected_events_map.pop(event_key, 0)
        event_count -= 1
        if event_count != 0: expected_events_map[event_key] = event_count

    if len(expected_events_map) > 0:
        missing_events = {}
        unexpected_events = {}
        for event_key,event_count in expected_events_map.items():
            if event_count > 0:
                if (event_key[0] == 'DeviceEvent') and (event_key[1] == EVENT_UPDATE):
                    continue # sometimes device update events, specially with massive port updates, might be lost
                missing_events[event_key] = event_count
            if event_count < 0:
                unexpected_events[event_key] = -event_count
        msg = ['EventCheck failed:']
        if len(missing_events) > 0: msg.append('missing_events={:s}'.format(str(missing_events)))
        if len(unexpected_events) > 0: msg.append('unexpected_events={:s}'.format(str(unexpected_events)))
        if len(msg) > 1: raise Exception(' '.join(msg))
