use qecs_core::{Event, BufferBase, EventBuffer, _EventBuffer};

use std::slice;

pub struct VecBuffer<E> {
    storage: Vec<E>,
}

impl<E> From<Vec<E>> for VecBuffer<E>
    where E: Event
{
    fn from(storage: Vec<E>) -> Self {
        VecBuffer{ storage: storage }
    }
}

impl<E> Default for VecBuffer<E>
    where E: Event
{
    fn default() -> Self {
        VecBuffer{ storage: Vec::default() }
    }
}

impl<E> BufferBase for VecBuffer<E> 
    where E: Event
{
    fn len(&self) -> usize { self.storage.len() }

    fn clear(&mut self) { self.storage.clear() }
}

pub type Iter<'a, E> = slice::Iter<'a, E>;

impl<'a, E> _EventBuffer<'a> for VecBuffer<E> 
    where E: Event
{
    type _Event = E;

    type Iter = Iter<'a, E>;
}

impl<E> EventBuffer for VecBuffer<E> 
    where E: Event
{
    type Event = E;

    fn write<T>(&mut self, ev: T)
        where T: Into<Self::Event>
    {
        self.storage.push(ev.into());
    }

    fn iter<'a>(&'a self) -> <Self as _EventBuffer<'a>>::Iter {
        self.storage.iter()
    }
}

impl<'a, E> IntoIterator for &'a VecBuffer<E> 
    where E: Event
{
    type Item = <Self::IntoIter as Iterator>::Item;
    type IntoIter = Iter<'a, E>;
    fn into_iter(self) -> Self::IntoIter { self.iter() }
}

