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

use glium::{Surface, VertexBuffer, Display, Texture2d, Program, Frame, DrawParameters, index::{NoIndices, PrimitiveType}, uniforms::SamplerWrapFunction, uniform, implement_vertex};
use glutin::surface::WindowSurface;
use glam::Mat4;
use png::ColorType;

use crate::world::ammo_crate::{AmmoCrate, RADIUS, MAX_TIME, FADE_IN_TIME};

use crate::app::filesystem::{Filesystem, FsBase};
use crate::utils::{texture, glium_resize};

#[derive(Clone, Copy)]
struct Vertex { v_pos: [f32; 2], v_tex_coords: [f32; 2] }
implement_vertex!(Vertex, v_pos, v_tex_coords);

#[derive(Clone, Copy)]
struct Instance { i_pos: [f32; 2], i_alpha: f32, i_scale: f32 }
implement_vertex!(Instance, i_pos, i_alpha, i_scale);

pub struct AmmoCrateRenderer {
	v_vbo: VertexBuffer<Vertex>,
	i_vbo: VertexBuffer<Instance>,
	texture: Texture2d,
	program: Program,
}

const FADE_OUT_TIME: f32 = 60.0;

impl AmmoCrateRenderer {
	pub fn new(display: &Display<WindowSurface>, fs: &Filesystem) -> AmmoCrateRenderer {
		static VERTICES: [Vertex; 4] = [
			Vertex { v_pos: [-RADIUS,  RADIUS], v_tex_coords: [0.0, 0.0] },
			Vertex { v_pos: [ RADIUS,  RADIUS], v_tex_coords: [1.0, 0.0] },
			Vertex { v_pos: [-RADIUS, -RADIUS], v_tex_coords: [0.0, 1.0] },
			Vertex { v_pos: [ RADIUS, -RADIUS], v_tex_coords: [1.0, 1.0] },
		];

		let vsh = fs::read_to_string(fs.get(FsBase::Static, Path::new("shaders/ammo_crate.vsh"))).unwrap();
		let fsh = fs::read_to_string(fs.get(FsBase::Static, Path::new("shaders/ammo_crate.fsh"))).unwrap();

		AmmoCrateRenderer {
			v_vbo: VertexBuffer::immutable(display, &VERTICES).unwrap(),
			i_vbo: VertexBuffer::empty_persistent(display, 0).unwrap(),
			texture: texture::load(display, &fs.get(FsBase::Static, Path::new("textures/ammo_crate.png")), ColorType::Rgba),
			program: Program::from_source(display, &vsh, &fsh, None).unwrap(),
		}
	}

	pub fn render(&mut self, ammo_crates: &[AmmoCrate], display: &Display<WindowSurface>, frame: &mut Frame, params: &DrawParameters, proj_matrix: &Mat4, time_shift: f32) {
		let count = ammo_crates.len();
		glium_resize::vbo_persistent(&mut self.i_vbo, display, count);

		{
			let mut buf = self.i_vbo.map_write();
			for (i, ac) in ammo_crates.iter().enumerate() {
				let time = ac.get_time() + time_shift;
				buf.set(i, Instance { i_pos: ac.get_pos().to_array(), i_alpha: AmmoCrateRenderer::get_alpha(time), i_scale: AmmoCrate::get_scale(time) });
			}
		}

		let uniforms = uniform! { u_matrix: proj_matrix.to_cols_array_2d(), u_texture: self.texture.sampled().wrap_function(SamplerWrapFunction::Clamp) };
		frame.draw((&self.v_vbo, self.i_vbo.slice(..count).unwrap().per_instance().unwrap()), NoIndices(PrimitiveType::TriangleStrip), &self.program, &uniforms, params).unwrap();
	}

	fn get_alpha(time: f32) -> f32 {
		if time < FADE_IN_TIME {
			time.max(0.0) / FADE_IN_TIME
		} else if time > MAX_TIME - FADE_OUT_TIME {
			(MAX_TIME - time.min(MAX_TIME)) / FADE_OUT_TIME
		} else {
			1.0
		}
	}

}
