// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use serde::{Serialize, Deserialize};
use glam::Vec2;

use crate::utils::maths::Rect;

pub const RADIUS: f32 = 1.0 / 3.0;
pub const MAX_TIME: f32 = 20.0 * 60.0;
pub const FADE_IN_TIME: f32 = 1.0;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmmoCrate {
	pos: Vec2,
	scale: f32, // Cached for physics calculations
	time: f32,
}

impl AmmoCrate {
	pub fn new(pos: Vec2) -> AmmoCrate {
		AmmoCrate { pos, scale: 0.0, time: 0.0 }
	}

	pub fn get_pos(&self) -> Vec2 {
		self.pos
	}

	pub fn get_scale(time: f32) -> f32 {
		if time < FADE_IN_TIME {
			let f = time.max(0.0) / FADE_IN_TIME;
			f * (2.0 - f)
		} else {
			1.0
		}
	}

	#[cfg(feature = "client")]
	pub fn get_time(&self) -> f32 {
		self.time
	}

	pub fn update(&mut self, dt: f32) -> bool {
		self.time += dt;
		self.scale = AmmoCrate::get_scale(self.time);
		self.time <= MAX_TIME
	}
}

impl Rect for AmmoCrate {
	fn get_p0(&self) -> Vec2 { self.pos - Vec2::splat(RADIUS * self.scale) }
	fn get_p1(&self) -> Vec2 { self.pos + Vec2::splat(RADIUS * self.scale) }
}
