use core::iter::{ExactSizeIterator, FusedIterator};
use core::marker::PhantomData;
use core::slice;

use crate::Key;
use crate::entry::Entry;

/// See [`Arena::iter`](crate::Arena::iter).
pub struct Iter<'a, K, V> {
    pub(crate) len: u32,
    pub(crate) slot: u32,
    pub(crate) inner: slice::Iter<'a, Entry<V>>,
    pub(crate) _key_type: PhantomData<K>,
}

impl<'a, K, V> Iterator for Iter<'a, K, V> {
    type Item = (Key<K>, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.len == 0 {
                return None;
            }

            let slot = self.slot;
            self.slot = self
                .slot
                .checked_add(1)
                .unwrap_or_else(|| unreachable!("Overflowed u32 trying to iterate Arena"));

            match self.inner.next()? {
                Entry::Empty(_) => (),
                Entry::Occupied(occupied) => {
                    self.len = self
                        .len
                        .checked_sub(1)
                        .unwrap_or_else(|| unreachable!("Underflowed u32 trying to iterate Arena"));

                    return Some((Key::new(slot, occupied.generation), &occupied.value));
                }
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len as usize, Some(self.len as usize))
    }
}

impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {}

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

    #[cfg(not(feature = "std"))]
    use alloc::vec::Vec;

    #[test]
    fn iter() {
        let mut arena = Arena::<(), u32>::with_capacity(2);
        let one = arena.insert(1);
        let two = arena.insert(2);

        let mut pairs = Vec::new();
        let mut iter = arena.iter();
        assert_eq!(iter.size_hint(), (2, Some(2)));

        let next = iter.next().unwrap();
        assert!(!pairs.contains(&next));
        pairs.push(next);
        assert_eq!(iter.size_hint(), (1, Some(1)));

        let next = iter.next().unwrap();
        assert!(!pairs.contains(&next));
        pairs.push(next);
        assert_eq!(iter.size_hint(), (0, Some(0)));

        assert_eq!(iter.next(), None);
        assert_eq!(iter.next(), None);
        assert_eq!(iter.size_hint(), (0, Some(0)));

        assert!(pairs.contains(&(one, &1)));
        assert!(pairs.contains(&(two, &2)));
    }
}
