use crate::error::TheatreError;
use crate::mailbox::address::MessageSender;
use crate::mailbox::Message;
use std::fmt::{Debug, Formatter};

/// An address parametrized of the message type instead of an Actor type.
/// This allows for collections of actors that may receive a particular message.
pub struct Recipient<M>
where
    M: Message,
{
    tx: Box<dyn MessageSender<M>>,
}

impl<M> Recipient<M>
where
    M: Message,
{
    pub(crate) fn new(sender: Box<dyn MessageSender<M>>) -> Self {
        Self { tx: sender }
    }

    pub async fn send(&mut self, msg: M) -> Result<<M as Message>::Return, TheatreError> {
        self.tx.send(msg).await
    }

    pub async fn try_send(&mut self, msg: M) -> Result<<M as Message>::Return, TheatreError> {
        self.tx.try_send(msg).await
    }

    pub fn try_send_and_forget(&mut self, msg: M) -> Result<(), TheatreError> {
        self.tx.try_send_and_forget(msg)
    }
}

impl<M> Clone for Recipient<M>
where
    M: Message,
{
    fn clone(&self) -> Self {
        self.tx.clone_recipient()
    }
}

impl<M> Debug for Recipient<M>
where
    M: Message + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Recipient<M>").field("tx", &"...").finish()
    }
}

#[cfg(test)]
mod test {
    use crate::prelude::*;

    struct A;

    impl Actor for A {}

    struct M;

    impl Message for M {
        type Return = bool;
    }

    #[async_trait]
    impl Handler<M> for A {
        async fn handle(&mut self, _: M, _: &mut Context<Self>) -> <M as Message>::Return {
            true
        }
    }

    #[tokio::test]
    async fn send_msg() {
        let addr = A.spawn().await;
        let mut recipient = addr.recipient();

        assert!(recipient.send(M).await.unwrap())
    }

    #[tokio::test]
    async fn try_send_msg() {
        let addr = A.spawn().await;
        let mut recipient = addr.recipient();
        assert!(recipient.try_send(M).await.unwrap())
    }

    #[tokio::test]
    async fn try_send_and_forget_msg() {
        let (addr, mut handle) = A.start().await;
        let mut recipient = addr.recipient();
        recipient.try_send_and_forget(M).unwrap();
        assert!(handle.heartbeat().await)
    }

    #[tokio::test]
    async fn clone_addr() {
        let (addr, mut handle) = A.start().await;
        let recipient = addr.recipient();
        let mut recipient2 = Recipient::clone(&recipient);

        assert!(recipient2.send(M).await.unwrap());
        assert!(handle.heartbeat().await)
    }
}
