use anyhow::Result;

use rtchallenge::{
    canvas::Canvas,
    matrices::Matrix4x4,
    rays::Ray,
    shapes::{intersect, Shape},
    tuples::{Color, Tuple},
    Float,
};

fn main() -> Result<()> {
    let w = 200;
    let h = w;
    let bg = Color::new(0.2, 0.2, 0.2);
    let mut c = Canvas::new(w, h, bg);
    let ray_origin = Tuple::point(0., 0., -5.);
    let wall_z = 10.;
    let wall_size = 7.;
    let pixel_size = wall_size / w as Float;
    let half = wall_size / 2.;
    let color = Color::new(1., 0., 0.);
    let mut shape = Shape::sphere();
    shape.set_transform(
        Matrix4x4::shearing(1., 0., 0., 0., 0., 0.) * Matrix4x4::scaling(0.5, 1., 1.0),
    );

    for y in 0..h {
        let world_y = half - pixel_size * y as Float;
        for x in 0..w {
            let world_x = -half + pixel_size * x as Float;
            let position = Tuple::point(world_x, world_y, wall_z);
            let r = Ray::new(ray_origin, (position - ray_origin).normalize());
            let xs = intersect(&shape, &r);
            if xs.hit().is_some() {
                c.set(x, y, color);
            }
        }
    }

    let path = "/tmp/eoc5.png";
    println!("saving output to {}", path);
    c.write_to_file(path)?;
    Ok(())
}
