use std::{fmt::Debug, ops::ControlFlow};

use crate::{Collector, assert_collector};

/// A [`Collector`] that searches for the first item satisfying a predicate.
///
/// If no matching item has been found, its [`Output`] is `None`.
/// When the collector encounters an item that makes the predicate return `true`,
/// it returns [`Break`], and the [`Output`] becomes `Some` containing that item.
///
/// This collector corresponds to [`Iterator::find()`].
///
/// # Examples
///
/// ```
/// use better_collect::{prelude::*, Find};
///
/// let mut collector = Find::new(|&x| x % 3 == 0);
///
/// assert!(collector.collect(1).is_continue());
/// assert!(collector.collect(5).is_continue());
///
/// // Found!
/// assert!(collector.collect(6).is_break());
///
/// assert_eq!(collector.finish(), Some(6));
/// ```
///
/// ```
/// use better_collect::{prelude::*, Find};
///
/// let mut collector = Find::new(|&x| x % 3 == 0);
///
/// assert!(collector.collect(1).is_continue());
/// assert!(collector.collect(5).is_continue());
/// assert!(collector.collect(-2).is_continue());
///
/// assert_eq!(collector.finish(), None);
/// ```
///
/// [`Break`]: std::ops::ControlFlow::Break
/// [`Output`]: Collector::Output
#[derive(Clone)]
pub struct Find<T, F> {
    state: State<T, F>,
}

#[derive(Clone)]
enum State<T, F> {
    Searching(F),
    Found(T),
}

impl<T, F> Find<T, F>
where
    F: FnMut(&T) -> bool,
{
    /// Creates an intance of this collector with a given predicate.
    #[inline]
    pub const fn new(pred: F) -> Self {
        assert_collector(Self {
            state: State::Searching(pred),
        })
    }
}

impl<T, F> Collector for Find<T, F>
where
    F: FnMut(&T) -> bool,
{
    type Item = T;

    type Output = Option<T>;

    fn collect(&mut self, item: Self::Item) -> ControlFlow<()> {
        if let State::Searching(ref mut pred) = self.state {
            if pred(&item) {
                self.state = State::Found(item);
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        } else {
            ControlFlow::Break(())
        }
    }

    #[inline]
    fn finish(self) -> Self::Output {
        if let State::Found(item) = self.state {
            Some(item)
        } else {
            None
        }
    }

    // Technically, we don't need to override it
    // since when this collector stops the method is useless anyway.
    // But we will have a support of `FUSED` const variable later,
    // making this neccessary.
    #[inline]
    fn break_hint(&self) -> bool {
        matches!(self.state, State::Found(_))
    }

    fn collect_many(&mut self, items: impl IntoIterator<Item = Self::Item>) -> ControlFlow<()> {
        if let State::Searching(ref mut pred) = self.state {
            if let Some(item) = items.into_iter().find(pred) {
                self.state = State::Found(item);
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        } else {
            ControlFlow::Break(())
        }
    }

    fn collect_then_finish(self, items: impl IntoIterator<Item = Self::Item>) -> Self::Output {
        match self.state {
            State::Searching(pred) => items.into_iter().find(pred),
            State::Found(item) => Some(item),
        }
    }
}

impl<T: Debug, F> Debug for Find<T, F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let item = if let State::Found(ref item) = self.state {
            Some(item)
        } else {
            None
        };

        f.debug_struct("Find").field("found", &item).finish()
    }
}
