use std::path::Path;

use crate::{interval::Interval, vec3::Color};

fn linear_to_gamma(linear_component: f64) -> f64 {
	if linear_component > 0.0 {
		return linear_component.sqrt();
	}

	0.0
}

pub fn write_image<P: AsRef<Path>>(
	path: P,
	image: &[Color],
	width: u32,
	height: u32,
) -> Result<(), image::ImageError> {
	let mut out = image::ImageBuffer::new(width, height);

	for (x, y, pixel) in out.enumerate_pixels_mut() {
		let index = (y * width) + x;

		let r = linear_to_gamma(image[index as usize].r());
		let g = linear_to_gamma(image[index as usize].g());
		let b = linear_to_gamma(image[index as usize].b());

		const INTENSITY: Interval = Interval::new(0.000, 0.999);

		*pixel = image::Rgb([
			(INTENSITY.clamp(r) * 256.0) as u8,
			(INTENSITY.clamp(g) * 256.0) as u8,
			(INTENSITY.clamp(b) * 256.0) as u8,
		]);
	}

	out.save(path)?;

	Ok(())
}
