use crate::{ReadableVec, VecIndex, VecValue};

use super::{AggFold, LazyAggVec};

impl<I, O, S1I, S2T, S1T, Strat> ReadableVec<I, O> for LazyAggVec<I, O, S1I, S2T, S1T, Strat>
where
    I: VecIndex,
    O: VecValue,
    S1I: VecIndex,
    S2T: VecValue,
    S1T: VecValue,
    Strat: AggFold<O, S1I, S2T, S1T>,
{
    fn read_into_at(&self, from: usize, to: usize, buf: &mut Vec<O>) {
        let mapping = (self.mapping)();
        let to = to.min(mapping.len());
        if from >= to {
            return;
        }
        buf.reserve(to - from);
        Strat::fold(&*self.source, &mapping, from, to, (), |(), v| buf.push(v));
    }

    fn for_each_range_dyn_at(&self, from: usize, to: usize, f: &mut dyn FnMut(O)) {
        let mapping = (self.mapping)();
        let to = to.min(mapping.len());
        if from >= to {
            return;
        }
        Strat::fold(&*self.source, &mapping, from, to, (), |(), v| f(v));
    }

    #[inline]
    fn fold_range_at<B, F: FnMut(B, O) -> B>(&self, from: usize, to: usize, init: B, f: F) -> B
    where
        Self: Sized,
    {
        let mapping = (self.mapping)();
        let to = to.min(mapping.len());
        if from >= to {
            return init;
        }
        Strat::fold(&*self.source, &mapping, from, to, init, f)
    }

    #[inline]
    fn try_fold_range_at<B, E, F: FnMut(B, O) -> std::result::Result<B, E>>(
        &self,
        from: usize,
        to: usize,
        init: B,
        f: F,
    ) -> std::result::Result<B, E>
    where
        Self: Sized,
    {
        let mapping = (self.mapping)();
        let to = to.min(mapping.len());
        if from >= to {
            return Ok(init);
        }
        Strat::try_fold(&*self.source, &mapping, from, to, init, f)
    }

    #[inline]
    fn collect_one_at(&self, index: usize) -> Option<O> {
        let mapping = (self.mapping)();
        if index >= mapping.len() {
            return None;
        }
        Strat::collect_one(&*self.source, &mapping, index)
    }
}
