//! Event management and forwarding
//!
//! It is recommended to read the
//! [sat-rs book chapter](https://absatsw.irs.uni-stuttgart.de/projects/sat-rs/book/events.html)
//! about events first.
//!
//! This module provides components to perform event routing. The most important component for this
//! task is the [EventManager]. It receives all events and then routes them to event subscribers
//! where appropriate.
//!
//! The event manager has a listener table abstracted by the [ListenerMap], which maps
//! listener groups identified by [ListenerKey]s to a [listener ID][ComponentId].
//! It also contains a sender table abstracted by the [SenderMap] which maps these sender
//! IDs to concrete [EventSender]s. A simple approach would be to use one send event provider
//! for each OBSW thread and then subscribe for all interesting events for a particular thread
//! using the send event provider ID.
//!
//! This can be done with the [EventManager] like this:
//!
//!  1. Provide a concrete [EventReceiver] implementation. This abstraction allow to use different
//!     message queue backends. A straightforward implementation where dynamic memory allocation is
//!     not a big concern would be to use the [std::sync::mpsc::Receiver] handle. The trait is
//!     already implemented for this type.
//!  2. To set up event creators, create channel pairs using some message queue implementation.
//!     Each event creator gets a (cloned) sender component which allows it to send events to the
//!     manager.
//!  3. The event manager receives the receiver component as part of a [EventReceiver]
//!     implementation so all events are routed to the manager.
//!  4. Create the [event sender map][SenderMap]s which allow routing events to
//!     subscribers. You can now use the subscriber component IDs to subscribe
//!     for event groups, for example by using the [EventManager::subscribe_single] method.
//!  5. Add the send provider as well using the [EventManager::add_sender] call so the event
//!     manager can route listener groups to a the send provider.
//!
//! Some components like a PUS Event Service or PUS Event Action Service might require all
//! events to package them as telemetry or start actions where applicable.
//! Other components might only be interested in certain events. For example, a thermal system
//! handler might only be interested in temperature events generated by a thermal sensor component.
//!
//! # Examples
//!
//! You can check [integration test](https://egit.irs.uni-stuttgart.de/rust/sat-rs/src/branch/main/satrs/tests/pus_events.rs)
//! for a concrete example using multi-threading where events are routed to
//! different threads.
//!
//! The [satrs-example](https://egit.irs.uni-stuttgart.de/rust/sat-rs/src/branch/main/satrs-example)
//! also contains a full event manager instance and exposes a test event via the PUS test service.
//! The [PUS event](https://egit.irs.uni-stuttgart.de/rust/sat-rs/src/branch/main/satrs-example/src/pus/event.rs)
//! module and the generic [events module](https://egit.irs.uni-stuttgart.de/rust/sat-rs/src/branch/main/satrs-example/src/events.rs)
//! show how the event management modules can be integrated into a more complex software.
use crate::{
    ComponentId,
    legacy::events::{Event, EventId, GroupId},
    queue::GenericSendError,
};
use core::marker::PhantomData;
use core::slice::Iter;

#[cfg(feature = "alloc")]
pub use alloc_mod::*;
#[cfg(feature = "std")]
pub use std_mod::*;

#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ListenerKey {
    Single(EventId),
    Group(GroupId),
    All,
}

#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct EventMessage<EventInstance> {
    sender_id: ComponentId,
    event: EventInstance,
}

impl<EventInstance: Event> EventMessage<EventInstance> {
    pub fn new(sender_id: ComponentId, event: EventInstance) -> Self {
        EventMessage { sender_id, event }
    }

    pub fn sender_id(&self) -> ComponentId {
        self.sender_id
    }

    pub fn event(&self) -> &EventInstance {
        &self.event
    }
}

/// Generic abstraction for event senders.
pub trait EventSender<EventInstance: Event> {
    type Error;

    /// Destination component ID.
    fn target_id(&self) -> ComponentId;

    fn send(&self, message: EventMessage<EventInstance>) -> Result<(), Self::Error>;
}

pub trait ListenerMap {
    #[cfg(feature = "alloc")]
    fn get_listeners(&self) -> alloc::vec::Vec<ListenerKey>;
    fn contains_listener(&self, key: &ListenerKey) -> bool;
    fn get_listener_ids(&self, key: &ListenerKey) -> Option<Iter<'_, ComponentId>>;
    fn add_listener(&mut self, key: ListenerKey, listener_id: ComponentId) -> bool;
    fn remove_duplicates(&mut self, key: &ListenerKey);
}

/// Generic abstraction for an event receiver.
pub trait EventReceiver<EventInstance: Event> {
    type Error;

    /// This function has to be provided by any event receiver. A call may or may not return
    /// an event.
    fn try_recv_event(&self) -> Result<Option<EventMessage<EventInstance>>, Self::Error>;
}

pub trait SenderMap<EventSenderInstance: EventSender<EventInstance>, EventInstance: Event> {
    fn contains_send_event_provider(&self, target_id: &ComponentId) -> bool;

    fn get_send_event_provider(&self, target_id: &ComponentId) -> Option<&EventSenderInstance>;
    fn add_send_event_provider(&mut self, send_provider: EventSenderInstance) -> bool;
}

/// Generic event manager implementation.
///
/// # Generics
///
///  * `EventReceiverInstance`: [EventReceiver] used to receive all events.
///  * `SenderMapInstance`: [SenderMap]  which maps channel IDs to send providers.
///  * `ListenerMapInstance`: [ListenerMap] which maps listener keys to channel IDs.
///  * `EventSenderInstance`: [EventSender] contained within the sender map which sends the events.
///  * `Event`: The event type. This type must implement the [Event] trait.
pub struct EventManager<
    EventReceiverInstance: EventReceiver<EventInstance>,
    SenderMapInstance: SenderMap<EventSenderInstance, EventInstance>,
    ListenerMapInstance: ListenerMap,
    EventSenderInstance: EventSender<EventInstance>,
    EventInstance: Event,
> {
    event_receiver: EventReceiverInstance,
    sender_map: SenderMapInstance,
    listener_map: ListenerMapInstance,
    phantom: core::marker::PhantomData<(EventSenderInstance, EventInstance)>,
}

#[derive(Debug)]
pub enum EventRoutingResult<EventInstance: Event> {
    /// No event was received
    Empty,
    /// An event was received and routed to listeners.
    Handled {
        num_recipients: u32,
        event_msg: EventMessage<EventInstance>,
    },
}

#[derive(Debug)]
pub enum EventRoutingError {
    Send(GenericSendError),
    NoSendersForKey(ListenerKey),
    NoSenderForId(ComponentId),
}

impl<
    EventReceiverInstance: EventReceiver<EventInstance>,
    SenderMapInstance: SenderMap<EventSenderInstance, EventInstance>,
    ListenerMapInstance: ListenerMap,
    EventSenderInstance: EventSender<EventInstance>,
    EventInstance: Event,
>
    EventManager<
        EventReceiverInstance,
        SenderMapInstance,
        ListenerMapInstance,
        EventSenderInstance,
        EventInstance,
    >
{
    pub fn remove_duplicates(&mut self, key: &ListenerKey) {
        self.listener_map.remove_duplicates(key)
    }

    /// Subscribe for a unique event.
    pub fn subscribe_single(&mut self, event: EventId, sender_id: ComponentId) {
        self.update_listeners(ListenerKey::Single(event), sender_id);
    }

    /// Subscribe for an event group.
    pub fn subscribe_group(&mut self, group_id: GroupId, sender_id: ComponentId) {
        self.update_listeners(ListenerKey::Group(group_id), sender_id);
    }

    /// Subscribe for all events received by the manager.
    ///
    /// For example, this can be useful for a handler component which sends every event as
    /// a telemetry packet.
    pub fn subscribe_all(&mut self, sender_id: ComponentId) {
        self.update_listeners(ListenerKey::All, sender_id);
    }
}
impl<
    EventReceiverInstance: EventReceiver<EventInstance>,
    SenderMapInstance: SenderMap<EventSenderInstance, EventInstance>,
    ListenerMapInstance: ListenerMap,
    EventSenderInstance: EventSender<EventInstance>,
    EventInstance: Event,
>
    EventManager<
        EventReceiverInstance,
        SenderMapInstance,
        ListenerMapInstance,
        EventSenderInstance,
        EventInstance,
    >
{
    pub fn new_with_custom_maps(
        event_receiver: EventReceiverInstance,
        sender_map: SenderMapInstance,
        listener_map: ListenerMapInstance,
    ) -> Self {
        EventManager {
            listener_map,
            sender_map,
            event_receiver,
            phantom: PhantomData,
        }
    }

    /// Add a new sender component which can be used to send events to subscribers.
    pub fn add_sender(&mut self, send_provider: EventSenderInstance) {
        if !self
            .sender_map
            .contains_send_event_provider(&send_provider.target_id())
        {
            self.sender_map.add_send_event_provider(send_provider);
        }
    }

    /// Generic function to update the event subscribers.
    fn update_listeners(&mut self, key: ListenerKey, sender_id: ComponentId) {
        self.listener_map.add_listener(key, sender_id);
    }
}

impl<
    EventReceiverInstance: EventReceiver<EventInstance>,
    SenderMapInstance: SenderMap<EventSenderInstance, EventInstance>,
    ListenerMapInstance: ListenerMap,
    EventSenderInstance: EventSender<EventInstance, Error = GenericSendError>,
    EventInstance: Event,
>
    EventManager<
        EventReceiverInstance,
        SenderMapInstance,
        ListenerMapInstance,
        EventSenderInstance,
        EventInstance,
    >
{
    /// This function will use the cached event receiver and try to receive one event.
    /// If an event was received, it will try to route that event to all subscribed event listeners.
    /// If this works without any issues, the [EventRoutingResult] will contain context information
    /// about the routed event.
    ///
    /// If an error occurs during the routing, the error handler will be called. The error handler
    /// should take a reference to the event message as the first argument, and the routing error
    /// as the second argument.
    pub fn try_event_handling<E: FnMut(&EventMessage<EventInstance>, EventRoutingError)>(
        &self,
        mut error_handler: E,
    ) -> EventRoutingResult<EventInstance> {
        let mut num_recipients = 0;
        let mut send_handler = |key: &ListenerKey, event_msg: &EventMessage<EventInstance>| {
            if self.listener_map.contains_listener(key) {
                if let Some(ids) = self.listener_map.get_listener_ids(key) {
                    for id in ids {
                        if let Some(sender) = self.sender_map.get_send_event_provider(id) {
                            if let Err(e) = sender.send(EventMessage::new(
                                event_msg.sender_id,
                                event_msg.event.clone(),
                            )) {
                                error_handler(event_msg, EventRoutingError::Send(e));
                            } else {
                                num_recipients += 1;
                            }
                        } else {
                            error_handler(event_msg, EventRoutingError::NoSenderForId(*id));
                        }
                    }
                } else {
                    error_handler(event_msg, EventRoutingError::NoSendersForKey(*key));
                }
            }
        };
        if let Ok(Some(event_msg)) = self.event_receiver.try_recv_event() {
            let single_key = ListenerKey::Single(event_msg.event().id());
            send_handler(&single_key, &event_msg);
            let group_key = ListenerKey::Group(event_msg.event().id().group_id());
            send_handler(&group_key, &event_msg);
            send_handler(&ListenerKey::All, &event_msg);
            return EventRoutingResult::Handled {
                num_recipients,
                event_msg,
            };
        }
        EventRoutingResult::Empty
    }
}

#[cfg(feature = "alloc")]
pub mod alloc_mod {
    use alloc::vec::Vec;
    use hashbrown::HashMap;

    use crate::legacy::events::EventErasedAlloc;

    use super::*;

    /// Helper type which constrains the sender map and listener map generics to the [DefaultSenderMap]
    /// and the [DefaultListenerMap]. It uses regular mpsc channels as the message queue backend.
    pub type EventManagerWithMpsc<EventInstance = EventErasedAlloc> = EventManager<
        EventDynParamReceiverMpsc,
        DefaultSenderMap<EventSenderMpsc<EventInstance>, EventInstance>,
        DefaultListenerMap,
        EventSenderMpsc<EventInstance>,
        EventInstance,
    >;

    /// Helper type which constrains the sender map and listener map generics to the [DefaultSenderMap]
    /// and the [DefaultListenerMap]. It uses
    /// [bounded mpsc senders](https://doc.rust-lang.org/std/sync/mpsc/struct.SyncSender.html) as the
    /// message queue backend.
    pub type EventManagerWithBoundedMpsc<EventInstance = EventErasedAlloc> = EventManager<
        EventDynParamReceiverMpsc,
        DefaultSenderMap<EventSenderMpscBounded<EventInstance>, EventInstance>,
        DefaultListenerMap,
        EventSenderMpscBounded<EventInstance>,
        EventInstance,
    >;

    impl<
        EventReceiverInstance: EventReceiver<EventInstance>,
        EventSenderInstance: EventSender<EventInstance>,
        EventInstance: Event,
    >
        EventManager<
            EventReceiverInstance,
            DefaultSenderMap<EventSenderInstance, EventInstance>,
            DefaultListenerMap,
            EventSenderInstance,
            EventInstance,
        >
    {
        /// Create an event manager where the sender table will be the [DefaultSenderMap]
        /// and the listener table will be the [DefaultListenerMap].
        pub fn new(event_receiver: EventReceiverInstance) -> Self {
            Self {
                listener_map: DefaultListenerMap::default(),
                sender_map: DefaultSenderMap::default(),
                event_receiver,
                phantom: PhantomData,
            }
        }
    }

    /// Default listener map.
    ///
    /// Simple implementation which uses a [HashMap] and a [Vec] internally.
    #[derive(Default)]
    pub struct DefaultListenerMap {
        listeners: HashMap<ListenerKey, Vec<ComponentId>>,
    }

    impl ListenerMap for DefaultListenerMap {
        fn get_listeners(&self) -> Vec<ListenerKey> {
            let mut key_list = Vec::new();
            for key in self.listeners.keys() {
                key_list.push(*key);
            }
            key_list
        }

        fn contains_listener(&self, key: &ListenerKey) -> bool {
            self.listeners.contains_key(key)
        }

        fn get_listener_ids(&self, key: &ListenerKey) -> Option<Iter<'_, ComponentId>> {
            self.listeners.get(key).map(|vec| vec.iter())
        }

        fn add_listener(&mut self, key: ListenerKey, sender_id: ComponentId) -> bool {
            if let Some(existing_list) = self.listeners.get_mut(&key) {
                existing_list.push(sender_id);
            } else {
                let new_list = alloc::vec![sender_id];
                self.listeners.insert(key, new_list);
            }
            true
        }

        fn remove_duplicates(&mut self, key: &ListenerKey) {
            if let Some(list) = self.listeners.get_mut(key) {
                list.sort_unstable();
                list.dedup();
            }
        }
    }

    /// Default sender map.
    ///
    /// Simple implementation which uses a [HashMap] internally.
    pub struct DefaultSenderMap<
        EventSenderInstance: EventSender<EventInstance>,
        EventInstance: Event,
    > {
        senders: HashMap<ComponentId, EventSenderInstance>,
        phantom: PhantomData<EventInstance>,
    }

    impl<EventSenderInstance: EventSender<EventInstance>, EventInstance: Event> Default
        for DefaultSenderMap<EventSenderInstance, EventInstance>
    {
        fn default() -> Self {
            Self {
                senders: Default::default(),
                phantom: Default::default(),
            }
        }
    }

    impl<EventSenderInstance: EventSender<EventInstance>, EventInstance: Event>
        SenderMap<EventSenderInstance, EventInstance>
        for DefaultSenderMap<EventSenderInstance, EventInstance>
    {
        fn contains_send_event_provider(&self, id: &ComponentId) -> bool {
            self.senders.contains_key(id)
        }

        fn get_send_event_provider(&self, id: &ComponentId) -> Option<&EventSenderInstance> {
            self.senders
                .get(id)
                .filter(|sender| sender.target_id() == *id)
        }

        fn add_send_event_provider(&mut self, send_provider: EventSenderInstance) -> bool {
            let id = send_provider.target_id();
            if self.senders.contains_key(&id) {
                return false;
            }
            self.senders.insert(id, send_provider).is_none()
        }
    }
}

#[cfg(feature = "std")]
pub mod std_mod {
    use crate::{
        legacy::events::{EventErasedAlloc, EventErasedHeapless},
        queue::GenericReceiveError,
    };

    use super::*;
    use std::sync::mpsc;

    impl<EventInstance: Event + Send> EventReceiver<EventInstance>
        for mpsc::Receiver<EventMessage<EventInstance>>
    {
        type Error = GenericReceiveError;

        fn try_recv_event(&self) -> Result<Option<EventMessage<EventInstance>>, Self::Error> {
            match self.try_recv() {
                Ok(msg) => Ok(Some(msg)),
                Err(e) => match e {
                    mpsc::TryRecvError::Empty => Ok(None),
                    mpsc::TryRecvError::Disconnected => {
                        Err(GenericReceiveError::TxDisconnected(None))
                    }
                },
            }
        }
    }

    pub type EventDynParamReceiverMpsc = mpsc::Receiver<EventMessage<EventErasedAlloc>>;
    pub type EventHeaplessReceiverMpsc<const N: usize> =
        mpsc::Receiver<EventMessage<EventErasedHeapless<N>>>;

    /// Generic event sender which uses a regular [mpsc::Sender] as the messaging backend to
    /// send events.
    #[derive(Clone)]
    pub struct EventSenderMpsc<EventInstance: Event + Send> {
        target_id: ComponentId,
        sender: mpsc::Sender<EventMessage<EventInstance>>,
    }

    impl<EventInstance: Event + Send> EventSenderMpsc<EventInstance> {
        pub fn new(
            target_id: ComponentId,
            sender: mpsc::Sender<EventMessage<EventInstance>>,
        ) -> Self {
            Self { target_id, sender }
        }
    }

    impl<EventInstance: Event + Send> EventSender<EventInstance> for EventSenderMpsc<EventInstance> {
        type Error = GenericSendError;

        fn target_id(&self) -> ComponentId {
            self.target_id
        }

        fn send(&self, event_msg: EventMessage<EventInstance>) -> Result<(), GenericSendError> {
            self.sender
                .send(event_msg)
                .map_err(|_| GenericSendError::RxDisconnected)
        }
    }

    /// Generic event sender which uses the [mpsc::SyncSender] as the messaging backend to send
    /// events. This has the advantage that the channel is bounded and thus more deterministic.
    #[derive(Clone)]
    pub struct EventSenderMpscBounded<EventInstance: Event + Send> {
        target_id: ComponentId,
        sender: mpsc::SyncSender<EventMessage<EventInstance>>,
        capacity: usize,
    }

    impl<EventInstance: Event + Send> EventSenderMpscBounded<EventInstance> {
        pub fn new(
            target_id: ComponentId,
            sender: mpsc::SyncSender<EventMessage<EventInstance>>,
            capacity: usize,
        ) -> Self {
            Self {
                target_id,
                sender,
                capacity,
            }
        }
    }

    impl<EventInstance: Event + Send> EventSender<EventInstance>
        for EventSenderMpscBounded<EventInstance>
    {
        type Error = GenericSendError;

        fn target_id(&self) -> ComponentId {
            self.target_id
        }

        fn send(&self, event_msg: EventMessage<EventInstance>) -> Result<(), Self::Error> {
            if let Err(e) = self.sender.try_send(event_msg) {
                return match e {
                    mpsc::TrySendError::Full(_) => {
                        Err(GenericSendError::QueueFull(Some(self.capacity as u32)))
                    }
                    mpsc::TrySendError::Disconnected(_) => Err(GenericSendError::RxDisconnected),
                };
            }
            Ok(())
        }
    }

    pub type EventDynParamSenderMpsc = EventSenderMpsc<EventErasedAlloc>;
    pub type EventHeaplessSenderMpsc<const N: usize> = EventSenderMpsc<EventErasedHeapless<N>>;
    pub type EventDynParamSenderMpscBounded = EventSenderMpscBounded<EventErasedAlloc>;
    pub type EventHeaplessSenderMpscBounded<const N: usize> =
        EventSenderMpscBounded<EventErasedHeapless<N>>;
}

#[cfg(test)]
mod tests {
    use arbitrary_int::u14;

    use super::*;
    use crate::legacy::events::{EventErasedAlloc, Severity};
    use crate::pus::test_util::{TEST_COMPONENT_ID_0, TEST_COMPONENT_ID_1};
    use std::sync::mpsc;

    const TEST_GROUP_ID_0: u14 = u14::new(0);
    const TEST_GROUP_ID_1: u14 = u14::new(1);

    #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, serde::Serialize, serde::Deserialize)]
    pub enum TestEvent {
        Info,
        Error,
        InfoWithParams(u16),
        OtherGroup,
    }

    impl Event for TestEvent {
        fn id(&self) -> EventId {
            match self {
                TestEvent::Info => EventId::new(Severity::Info, TEST_GROUP_ID_0, 0),
                TestEvent::Error => EventId::new(Severity::High, TEST_GROUP_ID_0, 1),
                TestEvent::InfoWithParams(_) => EventId::new(Severity::Info, TEST_GROUP_ID_0, 2),
                TestEvent::OtherGroup => EventId::new(Severity::Info, TEST_GROUP_ID_1, 0),
            }
        }
    }

    fn check_next_event(
        expected: TestEvent,
        receiver: &mpsc::Receiver<EventMessage<EventErasedAlloc>>,
    ) {
        if let Ok(event_msg) = receiver.try_recv() {
            assert_eq!(event_msg.event.id(), expected.id());
            let event: TestEvent = postcard::from_bytes(event_msg.event().raw()).unwrap();
            assert_eq!(event, expected);
        }
    }

    fn check_handled_event(
        res: EventRoutingResult<EventErasedAlloc>,
        expected: &EventErasedAlloc,
        expected_num_sent: u32,
        expected_sender_id: ComponentId,
    ) {
        assert!(matches!(res, EventRoutingResult::Handled { .. }));
        if let EventRoutingResult::Handled {
            num_recipients,
            event_msg,
        } = res
        {
            assert_eq!(event_msg.event, *expected);
            assert_eq!(event_msg.sender_id, expected_sender_id);
            assert_eq!(num_recipients, expected_num_sent);
        }
    }

    fn generic_event_man() -> (
        mpsc::Sender<EventMessage<EventErasedAlloc>>,
        EventManagerWithMpsc,
    ) {
        let (event_sender, event_receiver) = mpsc::channel();
        (event_sender, EventManager::new(event_receiver))
    }

    #[test]
    fn test_basic() {
        let (event_sender, mut event_man) = generic_event_man();
        let (single_event_sender, single_event_receiver) = mpsc::channel();
        let single_event_listener = EventSenderMpsc::new(0, single_event_sender);
        event_man.subscribe_single(TestEvent::Info.id(), single_event_listener.target_id());
        event_man.add_sender(single_event_listener);
        let (group_event_sender_0, group_event_receiver_0) = mpsc::channel();
        let group_event_listener = EventDynParamSenderMpsc::new(1, group_event_sender_0);
        event_man.subscribe_group(
            TestEvent::OtherGroup.id().group_id(),
            group_event_listener.target_id(),
        );
        event_man.add_sender(group_event_listener);

        let error_handler = |event_msg: &EventMessage<EventErasedAlloc>, e: EventRoutingError| {
            panic!("routing error occurred for event {:?}: {:?}", event_msg, e);
        };
        let event_grp_0 = EventErasedAlloc::new(&TestEvent::Info);
        let event_grp_1 = EventErasedAlloc::new(&TestEvent::OtherGroup);
        // Test event with one listener
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                event_grp_0.clone(),
            ))
            .expect("Sending single error failed");
        let res = event_man.try_event_handling(&error_handler);
        check_handled_event(res, &event_grp_0, 1, TEST_COMPONENT_ID_0.id());
        check_next_event(TestEvent::Info, &single_event_receiver);

        // Test event which is sent to all group listeners
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_1.id(),
                event_grp_1.clone(),
            ))
            .expect("Sending group error failed");
        let res = event_man.try_event_handling(&error_handler);
        check_handled_event(res, &event_grp_1, 1, TEST_COMPONENT_ID_1.id());
        check_next_event(TestEvent::OtherGroup, &group_event_receiver_0);
    }

    #[test]
    fn test_with_basic_params() {
        let error_handler = |event_msg: &EventMessage<EventErasedAlloc>, e: EventRoutingError| {
            panic!("routing error occurred for event {:?}: {:?}", event_msg, e);
        };
        let (event_sender, mut event_man) = generic_event_man();
        let event_0 = TestEvent::InfoWithParams(5);
        let (single_event_sender, single_event_receiver) = mpsc::channel();
        let single_event_listener = EventSenderMpsc::new(0, single_event_sender);
        event_man.subscribe_single(event_0.id(), single_event_listener.target_id());
        event_man.add_sender(single_event_listener);
        let event_0_erased = EventErasedAlloc::new(&event_0);
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                event_0_erased.clone(),
            ))
            .expect("Sending group error failed");
        let res = event_man.try_event_handling(&error_handler);
        check_handled_event(res, &event_0_erased, 1, TEST_COMPONENT_ID_0.id());
        check_next_event(event_0, &single_event_receiver);
    }

    /// Test listening for multiple groups
    #[test]
    fn test_multi_group() {
        let error_handler = |event_msg: &EventMessage<EventErasedAlloc>, e: EventRoutingError| {
            panic!("routing error occurred for event {:?}: {:?}", event_msg, e);
        };
        let (event_sender, mut event_man) = generic_event_man();
        let res = event_man.try_event_handling(error_handler);
        assert!(matches!(res, EventRoutingResult::Empty));

        let event_grp_0 = TestEvent::Info;
        let event_grp_1 = TestEvent::OtherGroup;
        let (event_grp_0_sender, event_grp_0_receiver) = mpsc::channel();
        let event_grp_0_and_1_listener = EventSenderMpsc::new(0, event_grp_0_sender);
        event_man.subscribe_group(
            event_grp_0.id().group_id(),
            event_grp_0_and_1_listener.target_id(),
        );
        event_man.subscribe_group(
            event_grp_1.id().group_id(),
            event_grp_0_and_1_listener.target_id(),
        );
        event_man.add_sender(event_grp_0_and_1_listener);

        let event_grp_0_erased = EventErasedAlloc::new(&event_grp_0);
        let event_grp_1_erased = EventErasedAlloc::new(&event_grp_1);
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                event_grp_0_erased.clone(),
            ))
            .expect("Sending Event Group 0 failed");
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_1.id(),
                event_grp_1_erased.clone(),
            ))
            .expect("Sendign Event Group 1 failed");
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_grp_0_erased, 1, TEST_COMPONENT_ID_0.id());
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_grp_1_erased, 1, TEST_COMPONENT_ID_1.id());

        check_next_event(event_grp_0, &event_grp_0_receiver);
        check_next_event(event_grp_1, &event_grp_0_receiver);
    }

    /// Test listening to the same event from multiple listeners. Also test listening
    /// to both group and single events from one listener
    #[test]
    fn test_listening_to_same_event_and_multi_type() {
        let error_handler = |event_msg: &EventMessage<EventErasedAlloc>, e: EventRoutingError| {
            panic!("routing error occurred for event {:?}: {:?}", event_msg, e);
        };
        let (event_sender, mut event_man) = generic_event_man();
        let event_0 = TestEvent::Info;
        let event_1 = TestEvent::OtherGroup;
        //let event_0 = EventU32::new(Severity::Info, 0, 5);
        //let event_1 = EventU32::new(Severity::High, 1, 0);
        let (event_0_tx_0, event_0_rx_0) = mpsc::channel();
        let (event_0_tx_1, event_0_rx_1) = mpsc::channel();
        let event_listener_0 = EventSenderMpsc::new(0, event_0_tx_0);
        let event_listener_1 = EventSenderMpsc::new(1, event_0_tx_1);
        let event_listener_0_sender_id = event_listener_0.target_id();
        event_man.subscribe_single(event_0.id(), event_listener_0_sender_id);
        event_man.add_sender(event_listener_0);
        let event_listener_1_sender_id = event_listener_1.target_id();
        event_man.subscribe_single(event_0.id(), event_listener_1_sender_id);
        event_man.add_sender(event_listener_1);
        let event_0_erased = EventErasedAlloc::new(&event_0);
        let event_1_erased = EventErasedAlloc::new(&event_1);
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                event_0_erased.clone(),
            ))
            .expect("Triggering Event 0 failed");
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_0_erased, 2, TEST_COMPONENT_ID_0.id());
        check_next_event(event_0, &event_0_rx_0);
        check_next_event(event_0, &event_0_rx_1);
        event_man.subscribe_group(event_1.id().group_id(), event_listener_0_sender_id);
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                event_0_erased.clone(),
            ))
            .expect("Triggering Event 0 failed");
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_1.id(),
                event_1_erased.clone(),
            ))
            .expect("Triggering Event 1 failed");

        // 3 Events messages will be sent now
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_0_erased, 2, TEST_COMPONENT_ID_0.id());
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_1_erased, 1, TEST_COMPONENT_ID_1.id());
        // Both the single event and the group event should arrive now
        check_next_event(event_0, &event_0_rx_0);
        check_next_event(event_1, &event_0_rx_0);

        // Do double insertion and then remove duplicates
        event_man.subscribe_group(event_1.id().group_id(), event_listener_0_sender_id);
        event_man.remove_duplicates(&ListenerKey::Group(event_1.id().group_id()));
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                event_1_erased.clone(),
            ))
            .expect("Triggering Event 1 failed");
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_1_erased, 1, TEST_COMPONENT_ID_0.id());
    }

    #[test]
    fn test_all_events_listener() {
        let error_handler = |event_msg: &EventMessage<EventErasedAlloc>, e: EventRoutingError| {
            panic!("routing error occurred for event {:?}: {:?}", event_msg, e);
        };
        let (event_sender, event_receiver) = mpsc::channel();
        let mut event_man = EventManagerWithMpsc::new(event_receiver);
        let event_0 = TestEvent::Info;
        let event_1 = TestEvent::Error;
        let (event_0_tx_0, all_events_rx) = mpsc::channel();
        let all_events_listener = EventSenderMpsc::new(0, event_0_tx_0);
        event_man.subscribe_all(all_events_listener.target_id());
        event_man.add_sender(all_events_listener);
        event_sender
            .send(EventMessage::new(TEST_COMPONENT_ID_0.id(), event_0.into()))
            .expect("Triggering event 0 failed");
        event_sender
            .send(EventMessage::new(TEST_COMPONENT_ID_1.id(), event_1.into()))
            .expect("Triggering event 1 failed");
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_0.into(), 1, TEST_COMPONENT_ID_0.id());
        let res = event_man.try_event_handling(error_handler);
        check_handled_event(res, &event_1.into(), 1, TEST_COMPONENT_ID_1.id());
        check_next_event(event_0, &all_events_rx);
        check_next_event(event_1, &all_events_rx);
    }

    #[test]
    fn test_bounded_event_sender_queue_full() {
        let (event_sender, _event_receiver) = mpsc::sync_channel(3);
        let test_event = TestEvent::Info;
        let event_sender = EventSenderMpscBounded::<EventErasedAlloc>::new(1, event_sender, 3);
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                test_event.into(),
            ))
            .expect("sending test event failed");
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                test_event.into(),
            ))
            .expect("sending test event failed");
        event_sender
            .send(EventMessage::new(
                TEST_COMPONENT_ID_0.id(),
                test_event.into(),
            ))
            .expect("sending test event failed");
        let error = event_sender.send(EventMessage::new(
            TEST_COMPONENT_ID_0.id(),
            test_event.into(),
        ));
        if let Err(e) = error {
            assert!(matches!(e, GenericSendError::QueueFull(Some(3))));
        } else {
            panic!("unexpected error {error:?}");
        }
    }
    #[test]
    fn test_bounded_event_sender_rx_dropped() {
        let (event_sender, event_receiver) = mpsc::sync_channel(3);
        let test_event = TestEvent::Info;
        let event_sender = EventSenderMpscBounded::<EventErasedAlloc>::new(1, event_sender, 3);
        drop(event_receiver);
        if let Err(e) = event_sender.send(EventMessage::new(
            TEST_COMPONENT_ID_0.id(),
            test_event.into(),
        )) {
            assert!(matches!(e, GenericSendError::RxDisconnected));
        } else {
            panic!("Expected error");
        }
    }
}
