use crate::ecs::text::components::{HudAnchor, HudText, TextProperties};
use crate::ecs::world::{Entity, Vec2, World};

pub fn load_font_from_bytes(
    world: &mut World,
    font_data: Vec<u8>,
    font_size: f32,
) -> Result<usize, String> {
    world.resources.pending_font_loads.push(PendingFontLoad {
        font_data,
        font_size,
    });

    let future_index = world.resources.text_cache.font_manager.font_count();
    Ok(future_index)
}

pub fn spawn_hud_text(
    world: &mut World,
    text: impl Into<String>,
    anchor: HudAnchor,
    position: Vec2,
) -> Entity {
    let text_index = world.resources.text_cache.add_text(text);
    let entity = world.spawn_entities(crate::ecs::world::HUD_TEXT, 1)[0];

    world.set_hud_text(
        entity,
        HudText::new(text_index)
            .with_position(position)
            .with_anchor(anchor),
    );

    entity
}

pub fn spawn_hud_text_with_properties(
    world: &mut World,
    text: impl Into<String>,
    anchor: HudAnchor,
    position: Vec2,
    properties: TextProperties,
) -> Entity {
    let text_index = world.resources.text_cache.add_text(text);
    let entity = world.spawn_entities(crate::ecs::world::HUD_TEXT, 1)[0];

    world.set_hud_text(
        entity,
        HudText::new(text_index)
            .with_position(position)
            .with_anchor(anchor)
            .with_properties(properties),
    );

    entity
}

pub struct PendingFontLoad {
    pub font_data: Vec<u8>,
    pub font_size: f32,
}

pub fn spawn_ui_text(
    world: &mut World,
    text: impl Into<String>,
    anchor: HudAnchor,
    position: Vec2,
) -> Entity {
    spawn_hud_text(world, text, anchor, position)
}

pub fn spawn_ui_text_with_properties(
    world: &mut World,
    text: impl Into<String>,
    anchor: HudAnchor,
    position: Vec2,
    properties: TextProperties,
) -> Entity {
    spawn_hud_text_with_properties(world, text, anchor, position, properties)
}
