// 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::{Vec2, Vec4, Mat4};
use png::ColorType;

use crate::app::filesystem::{Filesystem, FsBase};
use crate::world::{flag::{Flag, WIDTH, HEIGHT, X0, Y0}, player::PlayerId};
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_colour: [f32; 4] }
implement_vertex!(Instance, i_pos, i_colour);

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

impl FlagRenderer {
	pub fn new(display: &Display<WindowSurface>, fs: &Filesystem) -> FlagRenderer {
		static VERTICES: [Vertex; 4] = [
			Vertex { v_pos: [X0, Y0], v_tex_coords: [0.0, 1.0] },
			Vertex { v_pos: [X0 + WIDTH, Y0], v_tex_coords: [1.0, 1.0] },
			Vertex { v_pos: [X0, Y0 + HEIGHT], v_tex_coords: [0.0, 0.0] },
			Vertex { v_pos: [X0 + WIDTH, Y0 + HEIGHT], v_tex_coords: [1.0, 0.0] },
		];

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

		FlagRenderer {
			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/flag.png")), ColorType::Rgb),
			program: Program::from_source(display, &vsh, &fsh, None).unwrap(),
		}
	}

	#[allow(clippy::too_many_arguments)]
	pub fn render(&mut self, flags: &[Flag], display: &Display<WindowSurface>, frame: &mut Frame, params: &DrawParameters, proj_matrix: &Mat4, get_player_pos: impl Fn(PlayerId) -> Option<Vec2>, time_shift: f32) {
		let count = flags.len();
		glium_resize::vbo_persistent(&mut self.i_vbo, display, count);

		{
			let mut buf = self.i_vbo.map_write();
			for (i, flag) in flags.iter().enumerate() {
				let pos = flag.get_pos(&get_player_pos, time_shift);
				buf.set(i, Instance { i_pos: pos.to_array(), i_colour: Vec4::from(flag.get_colour()).to_array() });
			}
		}

		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();
	}
}
