use ray_tracing_core::{camera::Camera, prelude::*, renderer::ClassicalRenderer, scene::Scene};

pub struct PathTracerImportance {
    width: u32,
    height: u32,
}

impl PathTracerImportance {
    pub fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }
}

impl<S, C, R> ClassicalRenderer<R, S, C> for PathTracerImportance
where
    S: Scene<R>,
    C: Camera<R>,
    R: Rng,
{
    fn render_pixel(&self, scene: &S, camera: &C, x: u32, y: u32, rng: &mut R) -> Color {
        let mut sum = Color::black();
        let mut alpha = Color::white();

        let mut r = camera.forward(x, y, rng);

        let mut count = 0;

        while let Some(i) = scene.intersect(r, 0.001, Float::INFINITY) {
            let frame = i.tangent_frame();
            let w_in = frame.to_frame(-r.dir());

            if let Some(light) = i.light() {
                sum += alpha * light.emit(w_in, rng);
            }

            let w_out = if let Some(material) = i.material() {
                let sample_result = material.sample(w_in, rng);
                alpha *= sample_result.color();
                sample_result.w_out()
            } else {
                return sum;
            };

            r = Ray::new(r.at(i.t()), frame.to_world(w_out), r.time());
            count += 1;
            if count > 4 {
                break;
            }
        }

        sum
    }

    fn width(&self) -> u32 {
        self.width
    }

    fn height(&self) -> u32 {
        self.height
    }
}
