use crate::ecs::world::World;
use crate::render::wgpu::text_mesh::generate_text_mesh;

pub fn sync_text_meshes_system(world: &mut World) {
    let entities: Vec<_> = world.query_entities(crate::ecs::world::TEXT).collect();

    for entity in entities {
        let (text_index, font_index, properties, is_dirty) = {
            if let Some(text) = world.get_text(entity) {
                if !text.dirty {
                    continue;
                }
                (
                    text.text_index,
                    text.font_index,
                    text.properties.clone(),
                    text.dirty,
                )
            } else {
                continue;
            }
        };

        if !is_dirty {
            continue;
        }

        let text_content = world.resources.text_cache.get_text(text_index);
        if text_content.is_none() {
            continue;
        }
        let text_content = text_content.unwrap();

        let font = world.resources.text_cache.font_manager.get_font(font_index);
        if font.is_none() {
            continue;
        }
        let font = font.unwrap();

        let mesh = generate_text_mesh(text_content, font, &properties);

        if let Some(text) = world.get_text_mut(entity) {
            text.cached_mesh = Some(mesh);
            text.dirty = false;
        }
    }
}

pub fn sync_hud_text_system(world: &mut World) {
    let entities: Vec<_> = world.query_entities(crate::ecs::world::HUD_TEXT).collect();

    for entity in entities {
        let (text_index, font_index, properties, is_dirty) = {
            if let Some(hud_text) = world.get_hud_text(entity) {
                if !hud_text.dirty {
                    continue;
                }
                (
                    hud_text.text_index,
                    hud_text.font_index,
                    hud_text.properties.clone(),
                    hud_text.dirty,
                )
            } else {
                continue;
            }
        };

        if !is_dirty {
            continue;
        }

        let text_content = world.resources.text_cache.get_text(text_index);
        if text_content.is_none() {
            continue;
        }
        let text_content = text_content.unwrap();

        let font = world.resources.text_cache.font_manager.get_font(font_index);
        if font.is_none() {
            continue;
        }
        let font = font.unwrap();

        let mesh = generate_text_mesh(text_content, font, &properties);

        if let Some(hud_text) = world.get_hud_text_mut(entity) {
            hud_text.cached_mesh = Some(mesh);
            hud_text.dirty = false;
        }
    }
}
