use crate::fm_demod::Sample;

pub struct LowPass<I> {
    inner: I,
    y_prev: Sample,
    alpha: f32,
}

impl<I> LowPass<I> {
    pub fn new(inner: I, alpha: f32) -> Self {
        Self {
            inner,
            y_prev: 0.0,
            alpha,
        }
    }

    pub fn process_sample(&mut self, x_n: Sample) -> Sample {
        let y_n = self.alpha * x_n + (1.0 - self.alpha) * self.y_prev;

        self.y_prev = y_n;

        y_n
    }
}

impl<I, E> Iterator for LowPass<I>
where
    I: Iterator<Item = Result<Sample, E>>,
{
    type Item = Result<Sample, E>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.inner.next()? {
            Ok(sample) => Some(Ok(self.process_sample(sample))),
            Err(e) => Some(Err(e)),
        }
    }
}
