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

use super::image::Image;
use super::inkscape;

use crate::utils;

const HUMAN_INPUT: &str = "data/player_human.svg";
const BOT_INPUT: &str = "data/player_bot.svg";
const OUTPUT: &str = "../data/textures/players.png";

struct Texture {
	path: &'static str,
	name: &'static str,
}

pub fn generate() {
	const SIZE: usize = 256;

	let textures = [
		Texture { path: HUMAN_INPUT, name: "player_human" },
		Texture { path: BOT_INPUT, name: "player_bot" },
	];

	let (width, height) = (SIZE, SIZE / 2 * textures.len());
	let mut pixels = Vec::with_capacity(width * height * 2);

	// At least one input nexture needs to be newer than the output
	let output_time = utils::modified_time_output(OUTPUT);
	if textures.iter().all(|texture| utils::modified_time_input(texture.path) <= output_time) {
		return;
	}

	for texture in textures {
		let image = inkscape::gen_grey_layers(texture.name, texture.path, &["base", "colour"], SIZE, SIZE / 2);
		assert_eq!(image.width, SIZE);
		assert_eq!(image.height, SIZE / 2);
		pixels.append(&mut image.pixels.into_vec());
	}

	let pixels = pixels.into_boxed_slice();
	Image { width, height, pixels }.save(OUTPUT, ColorType::GrayscaleAlpha);
}

pub fn generate_icon(size: usize, path: &str) {
	let input = inkscape::gen_grey_layers("player_human", HUMAN_INPUT, &["base", "colour", "alpha"], size, size / 2);

	let mut output = Image::new(size, size, 4);
	let player_colour = [255, 63, 31];

	assert!(input.width == size && input.height == size / 2);

	for y in 0..size / 2 {
		for x in 0..size {
			let i = x + y * size;
			let base = input.pixels[i * 3];
			let colour = input.pixels[i * 3 + 1];
			let alpha = input.pixels[i * 3 + 2];
			let t = colour as f64 / 255.0;

			let out_indices = [
				x + y * size,
				x + (size - 1 - y) * size,
			];

			for out_i in out_indices {
				for (i, &colour) in player_colour.iter().enumerate() {
					output.pixels[out_i * 4 + i] = (base as i32 + ((colour - base as i32) as f64 * t) as i32) as u8;
				}

				output.pixels[out_i * 4 + 3] = alpha;
			}
		}
	}

	output.save(path, ColorType::Rgba);
}
