use crate::ecs::world::World;
use nalgebra_glm::Vec2;

const FIRST_USER_SLOT: u32 = 1;
const LAST_USER_SLOT: u32 = 119;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SpriteSlotAllocator {
    pub next_slot: u32,
}

impl Default for SpriteSlotAllocator {
    fn default() -> Self {
        Self {
            next_slot: FIRST_USER_SLOT,
        }
    }
}

pub fn allocate_sprite_slot(world: &mut World) -> u32 {
    let slot = world.resources.sprite_slot_allocator.next_slot;
    assert!(
        slot <= LAST_USER_SLOT,
        "Sprite slot allocator exhausted: all {} user slots are in use",
        LAST_USER_SLOT
    );
    world.resources.sprite_slot_allocator.next_slot = slot + 1;
    slot
}

pub fn sized_slot_uv(texture_width: u32, texture_height: u32) -> (Vec2, Vec2) {
    let slot_size = crate::render::wgpu::sprite_texture_atlas::SPRITE_ATLAS_SLOT_SIZE;
    let half_texel_x = 0.5 / slot_size.0 as f32;
    let half_texel_y = 0.5 / slot_size.1 as f32;
    let uv_min = Vec2::new(half_texel_x, half_texel_y);
    let uv_max = Vec2::new(
        texture_width as f32 / slot_size.0 as f32 - half_texel_x,
        texture_height as f32 / slot_size.1 as f32 - half_texel_y,
    );
    (uv_min, uv_max)
}
