use crate::safe_lock_option_observer;
use crate::utils::types::{Mutable, MutableHelper, NecessarySendSync, Shared};
use crate::{
    disposable::subscription::Subscription,
    observable::Observable,
    observer::{Observer, Termination},
    utils::unsub_after_termination::subscribe_unsub_after_termination,
};
use educe::Educe;
use std::collections::VecDeque;

/// Combines the emissions of multiple Observables together via a specified function and emits single items for each combination based on the sequence of their emissions.
/// See <https://reactivex.io/documentation/operators/zip.html>
///
/// # Examples
/// ```rust
/// use rx_rust::{
///     observable::observable_ext::ObservableExt,
///     observer::Termination,
///     operators::{
///         combining::zip::Zip,
///         creating::from_iter::FromIter,
///     },
/// };
///
/// let mut values = Vec::new();
/// let mut terminations = Vec::new();
///
/// let observable = Zip::new(
///     FromIter::new(vec![1, 2]),
///     FromIter::new(vec![10, 20]),
/// );
/// observable.subscribe_with_callback(
///     |value| values.push(value),
///     |termination| terminations.push(termination),
/// );
///
/// assert_eq!(values, vec![(1, 10), (2, 20)]);
/// assert_eq!(terminations, vec![Termination::Completed]);
/// ```
#[derive(Educe)]
#[educe(Debug, Clone)]
pub struct Zip<OE1, OE2> {
    source_1: OE1,
    source_2: OE2,
}

impl<OE1, OE2> Zip<OE1, OE2> {
    pub fn new<'or, 'sub, T1, T2, E>(source_1: OE1, source_2: OE2) -> Self
    where
        OE1: Observable<'or, 'sub, T1, E>,
        OE2: Observable<'or, 'sub, T2, E>,
    {
        Self { source_1, source_2 }
    }
}

impl<'or, 'sub, T1, T2, E, OE1, OE2> Observable<'or, 'sub, (T1, T2), E> for Zip<OE1, OE2>
where
    T1: NecessarySendSync + 'or,
    T2: NecessarySendSync + 'or,
    OE1: Observable<'or, 'sub, T1, E>,
    OE2: Observable<'or, 'sub, T2, E>,
    'sub: 'or,
{
    fn subscribe(
        self,
        observer: impl Observer<(T1, T2), E> + NecessarySendSync + 'or,
    ) -> Subscription<'sub> {
        subscribe_unsub_after_termination(observer, |observer| {
            let observer = Shared::new(Mutable::new(Some(observer)));
            let buffer = Shared::new(Mutable::new(ZipObserverBufferState::None));
            let observer_1 = ZipObserver1 {
                observer: observer.clone(),
                buffer: buffer.clone(),
            };
            let observer_2 = ZipObserver2 { observer, buffer };
            let subscription_1 = self.source_1.subscribe(observer_1);
            let subscription_2 = self.source_2.subscribe(observer_2);
            subscription_1 + subscription_2
        })
    }
}

enum ZipObserverBufferState<T1, T2> {
    None,
    One {
        buffer: VecDeque<T1>,
        is_completed: bool,
    },
    Two {
        buffer: VecDeque<T2>,
        is_completed: bool,
    },
}

struct ZipObserver1<T1, T2, OR> {
    observer: Shared<Mutable<Option<OR>>>,
    buffer: Shared<Mutable<ZipObserverBufferState<T1, T2>>>,
}

impl<T1, T2, E, OR> Observer<T1, E> for ZipObserver1<T1, T2, OR>
where
    OR: Observer<(T1, T2), E>,
{
    fn on_next(&mut self, value: T1) {
        self.buffer.lock_mut(|mut lock| match &mut *lock {
            ZipObserverBufferState::None => {
                *lock = ZipObserverBufferState::One {
                    buffer: VecDeque::from([value]),
                    is_completed: false,
                };
            }
            ZipObserverBufferState::One { buffer: items, .. } => {
                items.push_back(value);
            }
            ZipObserverBufferState::Two {
                buffer: items,
                is_completed,
            } => {
                let item = items.pop_front().unwrap();
                let should_complete;
                if items.is_empty() {
                    should_complete = *is_completed;
                    *lock = ZipObserverBufferState::None;
                } else {
                    should_complete = false;
                }
                drop(lock);
                if should_complete {
                    safe_lock_option_observer!(on_next_and_termination: self.observer, (value, item), Termination::Completed);
                } else {
                    safe_lock_option_observer!(on_next: self.observer, (value, item));
                }
            }
        });
    }

    fn on_termination(self, termination: Termination<E>) {
        let should_terminate = match termination {
            Termination::Completed => self.buffer.lock_mut(|mut lock| match &mut *lock {
                ZipObserverBufferState::None => true,
                ZipObserverBufferState::One { is_completed, .. } => {
                    *is_completed = true;
                    false
                }
                ZipObserverBufferState::Two { .. } => true,
            }),
            Termination::Error(_) => true,
        };
        if should_terminate {
            safe_lock_option_observer!(on_termination: self.observer, termination);
        }
    }
}

struct ZipObserver2<T1, T2, OR> {
    observer: Shared<Mutable<Option<OR>>>,
    buffer: Shared<Mutable<ZipObserverBufferState<T1, T2>>>,
}

impl<T1, T2, E, OR> Observer<T2, E> for ZipObserver2<T1, T2, OR>
where
    OR: Observer<(T1, T2), E>,
{
    fn on_next(&mut self, value: T2) {
        self.buffer.lock_mut(|mut lock| match &mut *lock {
            ZipObserverBufferState::None => {
                *lock = ZipObserverBufferState::Two {
                    buffer: VecDeque::from([value]),
                    is_completed: false,
                };
            }
            ZipObserverBufferState::One {
                buffer: items,
                is_completed,
            } => {
                let item = items.pop_front().unwrap();
                let should_complete;
                if items.is_empty() {
                    should_complete = *is_completed;
                    *lock = ZipObserverBufferState::None;
                } else {
                    should_complete = false;
                }
                drop(lock);
                if should_complete {
                    safe_lock_option_observer!(on_next_and_termination: self.observer, (item, value), Termination::Completed);
                } else {
                    safe_lock_option_observer!(on_next: self.observer, (item, value));
                }
            }
            ZipObserverBufferState::Two { buffer: items, .. } => {
                items.push_back(value);
            }
        });
    }

    fn on_termination(self, termination: Termination<E>) {
        let should_terminate = match termination {
            Termination::Completed => self.buffer.lock_mut(|mut lock| match &mut *lock {
                ZipObserverBufferState::None => true,
                ZipObserverBufferState::One { .. } => true,
                ZipObserverBufferState::Two { is_completed, .. } => {
                    *is_completed = true;
                    false
                }
            }),
            Termination::Error(_) => true,
        };
        if should_terminate {
            safe_lock_option_observer!(on_termination: self.observer, termination);
        }
    }
}
