// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use std::path::Path;

use png::ColorType;

use super::Vm;

use crate::utils::{texture::Image, directory_traversal};

impl Vm {
	pub(super) fn load_image(&mut self, path: &Path) -> Result<(), String> {
		let image = Image::try_new(&self.config_dir.join(directory_traversal::prevent(path)?), ColorType::Grayscale)?;
		if image.width != self.grid_size.x || image.height != self.grid_size.y {
			return Err(format!("image size of {}x{} doesn't match grid size of {}x{}", image.width, image.height, self.grid_size.x, self.grid_size.y));
		}

		let mut bmap = Vec::with_capacity(self.block_count);
		for y in (0..image.height).rev() {
			let i = (y * image.width) as usize;
			bmap.extend(image.pixels[i..i + image.width as usize].iter().map(|&x| x as f32 / 255.0));
		}

		self.stack.push(bmap.into_boxed_slice());
		Ok(())
	}
}
