use super::{Subject, publish_subject::PublishSubject};
use crate::utils::types::{Mutable, NecessarySendSync, Shared};
use crate::{
    disposable::subscription::Subscription,
    observable::Observable,
    observer::{Observer, Termination},
};
use crate::{safe_lock, safe_lock_option};
use educe::Educe;

/// Remembers only the last emission and replays it on completion.
#[derive(Educe)]
#[educe(Debug, Clone, Default)]
pub struct AsyncSubject<'or, T, E> {
    value: Shared<Mutable<Option<T>>>,
    publish_subject: PublishSubject<'or, T, E>,
}

impl<T, E> AsyncSubject<'_, T, E> {
    pub fn new() -> Self {
        Self {
            value: Shared::new(Mutable::new(None)),
            publish_subject: PublishSubject::default(),
        }
    }
}

impl<'or, 'sub, T, E> Observable<'or, 'sub, T, E> for AsyncSubject<'or, T, E>
where
    T: Clone + NecessarySendSync + 'sub,
    E: Clone + NecessarySendSync + 'sub,
    'or: 'sub,
{
    fn subscribe(
        self,
        mut observer: impl Observer<T, E> + NecessarySendSync + 'or,
    ) -> Subscription<'sub> {
        if let Some(terminated) = self.terminated() {
            match &terminated {
                Termination::Completed => {
                    if let Some(value) = safe_lock!(clone: self.value) {
                        observer.on_next(value);
                    }
                }
                Termination::Error(_) => {}
            }
            observer.on_termination(terminated);
            Subscription::default()
        } else {
            self.publish_subject.subscribe(observer)
        }
    }
}

impl<T, E> Observer<T, E> for AsyncSubject<'_, T, E>
where
    T: Clone + NecessarySendSync,
    E: Clone + NecessarySendSync,
{
    fn on_next(&mut self, value: T) {
        if self.terminated().is_none() {
            safe_lock_option!(replace: self.value, value);
        }
    }

    fn on_termination(mut self, termination: Termination<E>) {
        match &termination {
            Termination::Completed => {
                if let Some(value) = safe_lock!(clone: self.value) {
                    self.publish_subject.on_next(value);
                }
            }
            Termination::Error(_) => {}
        }
        self.publish_subject.on_termination(termination);
    }
}

impl<'or, 'sub, T, E> Subject<'or, 'sub, T, E> for AsyncSubject<'or, T, E>
where
    T: Clone + NecessarySendSync + 'sub,
    E: Clone + NecessarySendSync + 'sub,
    'or: 'sub,
{
    fn terminated(&self) -> Option<Termination<E>>
    where
        E: Clone,
    {
        self.publish_subject.terminated()
    }
}
