use std::collections::HashMap;
use std::sync::{Arc, Weak};
use std::time::Duration;
use async_trait::async_trait;
use tokio::sync::{mpsc, Mutex, RwLock};
use tokio::{io, time};
use crate::common::{Id, Response, UntypedResponse};
#[derive(Clone, Debug)]
pub struct PostOffice<T> {
    mailboxes: Arc<Mutex<HashMap<Id, mpsc::Sender<T>>>>,
    default_box: Arc<RwLock<Option<mpsc::Sender<T>>>>,
}
impl<T> Default for PostOffice<T>
where
    T: Send + 'static,
{
    fn default() -> Self {
        Self::new(Duration::from_secs(60))
    }
}
impl<T> PostOffice<T>
where
    T: Send + 'static,
{
    pub fn new(cleanup: Duration) -> Self {
        let mailboxes = Arc::new(Mutex::new(HashMap::new()));
        let mref = Arc::downgrade(&mailboxes);
        tokio::spawn(async move {
            while let Some(m) = Weak::upgrade(&mref) {
                m.lock()
                    .await
                    .retain(|_id, tx: &mut mpsc::Sender<T>| !tx.is_closed());
                drop(m);
                time::sleep(cleanup).await;
            }
        });
        Self {
            mailboxes,
            default_box: Arc::new(RwLock::new(None)),
        }
    }
    pub async fn make_mailbox(&self, id: Id, buffer: usize) -> Mailbox<T> {
        let (tx, rx) = mpsc::channel(buffer);
        self.mailboxes.lock().await.insert(id.clone(), tx);
        Mailbox {
            id,
            rx: Box::new(rx),
        }
    }
    pub async fn deliver(&self, id: &Id, value: T) -> bool {
        if let Some(tx) = self.mailboxes.lock().await.get_mut(id) {
            let success = tx.send(value).await.is_ok();
            if !success {
                self.mailboxes.lock().await.remove(id);
            }
            success
        } else if let Some(tx) = self.default_box.read().await.as_ref() {
            tx.send(value).await.is_ok()
        } else {
            false
        }
    }
    pub async fn assign_default_mailbox(&self, buffer: usize) -> Mailbox<T> {
        let (tx, rx) = mpsc::channel(buffer);
        *self.default_box.write().await = Some(tx);
        Mailbox {
            id: "".to_string(),
            rx: Box::new(rx),
        }
    }
    pub async fn remove_default_mailbox(&self) {
        *self.default_box.write().await = None;
    }
    pub async fn has_default_mailbox(&self) -> bool {
        self.default_box.read().await.is_some()
    }
    pub async fn cancel(&self, id: &Id) {
        self.mailboxes.lock().await.remove(id);
    }
    pub async fn cancel_many(&self, ids: impl Iterator<Item = &Id>) {
        let mut lock = self.mailboxes.lock().await;
        for id in ids {
            lock.remove(id);
        }
    }
    pub async fn cancel_all(&self) {
        self.mailboxes.lock().await.clear();
    }
}
impl<T> PostOffice<Response<T>>
where
    T: Send + 'static,
{
    pub async fn deliver_response(&self, res: Response<T>) -> bool {
        self.deliver(&res.origin_id.clone(), res).await
    }
}
impl PostOffice<UntypedResponse<'static>> {
    pub async fn deliver_untyped_response(&self, res: UntypedResponse<'static>) -> bool {
        self.deliver(&res.origin_id.clone().into_owned(), res).await
    }
}
pub enum MailboxTryNextError {
    Empty,
    Closed,
}
#[async_trait]
trait MailboxReceiver: Send + Sync {
    type Output;
    fn try_recv(&mut self) -> Result<Self::Output, MailboxTryNextError>;
    async fn recv(&mut self) -> Option<Self::Output>;
    fn close(&mut self);
}
#[async_trait]
impl<T: Send> MailboxReceiver for mpsc::Receiver<T> {
    type Output = T;
    fn try_recv(&mut self) -> Result<Self::Output, MailboxTryNextError> {
        match mpsc::Receiver::try_recv(self) {
            Ok(x) => Ok(x),
            Err(mpsc::error::TryRecvError::Empty) => Err(MailboxTryNextError::Empty),
            Err(mpsc::error::TryRecvError::Disconnected) => Err(MailboxTryNextError::Closed),
        }
    }
    async fn recv(&mut self) -> Option<Self::Output> {
        mpsc::Receiver::recv(self).await
    }
    fn close(&mut self) {
        mpsc::Receiver::close(self)
    }
}
struct MappedMailboxReceiver<T, U> {
    rx: Box<dyn MailboxReceiver<Output = T>>,
    f: Box<dyn Fn(T) -> U + Send + Sync>,
}
#[async_trait]
impl<T: Send, U: Send> MailboxReceiver for MappedMailboxReceiver<T, U> {
    type Output = U;
    fn try_recv(&mut self) -> Result<Self::Output, MailboxTryNextError> {
        match self.rx.try_recv() {
            Ok(x) => Ok((self.f)(x)),
            Err(x) => Err(x),
        }
    }
    async fn recv(&mut self) -> Option<Self::Output> {
        let value = self.rx.recv().await?;
        Some((self.f)(value))
    }
    fn close(&mut self) {
        self.rx.close()
    }
}
struct MappedOptMailboxReceiver<T, U> {
    rx: Box<dyn MailboxReceiver<Output = T>>,
    f: Box<dyn Fn(T) -> Option<U> + Send + Sync>,
}
#[async_trait]
impl<T: Send, U: Send> MailboxReceiver for MappedOptMailboxReceiver<T, U> {
    type Output = U;
    fn try_recv(&mut self) -> Result<Self::Output, MailboxTryNextError> {
        match self.rx.try_recv() {
            Ok(x) => match (self.f)(x) {
                Some(x) => Ok(x),
                None => Err(MailboxTryNextError::Empty),
            },
            Err(x) => Err(x),
        }
    }
    async fn recv(&mut self) -> Option<Self::Output> {
        loop {
            let value = self.rx.recv().await?;
            if let Some(x) = (self.f)(value) {
                return Some(x);
            }
        }
    }
    fn close(&mut self) {
        self.rx.close()
    }
}
pub struct Mailbox<T> {
    id: Id,
    rx: Box<dyn MailboxReceiver<Output = T>>,
}
impl<T> Mailbox<T> {
    pub fn id(&self) -> &Id {
        &self.id
    }
    pub fn try_next(&mut self) -> Result<T, MailboxTryNextError> {
        self.rx.try_recv()
    }
    pub async fn next(&mut self) -> Option<T> {
        self.rx.recv().await
    }
    pub async fn next_timeout(&mut self, duration: Duration) -> io::Result<Option<T>> {
        time::timeout(duration, self.next())
            .await
            .map_err(|x| io::Error::new(io::ErrorKind::TimedOut, x))
    }
    pub fn close(&mut self) {
        self.rx.close()
    }
}
impl<T: Send + 'static> Mailbox<T> {
    pub fn map<U: Send + 'static>(self, f: impl Fn(T) -> U + Send + Sync + 'static) -> Mailbox<U> {
        Mailbox {
            id: self.id,
            rx: Box::new(MappedMailboxReceiver {
                rx: self.rx,
                f: Box::new(f),
            }),
        }
    }
    pub fn map_opt<U: Send + 'static>(
        self,
        f: impl Fn(T) -> Option<U> + Send + Sync + 'static,
    ) -> Mailbox<U> {
        Mailbox {
            id: self.id,
            rx: Box::new(MappedOptMailboxReceiver {
                rx: self.rx,
                f: Box::new(f),
            }),
        }
    }
}