use crate::ecs::EditorWorld;
use nightshade::prelude::*;

#[derive(Default, Clone)]
pub struct OverlayHandles {
    pub fps_panel: Entity,
    pub fps_label: Entity,
}

pub fn build(tree: &mut UiTreeBuilder) -> OverlayHandles {
    let fps_panel = tree.add_floating_panel(
        "fps_overlay",
        "FPS",
        Rect {
            min: vec2(20.0, 60.0),
            max: vec2(160.0, 116.0),
        },
    );
    ui_panel_set_header_visible(tree.world_mut(), fps_panel, false);
    ui_set_visible(tree.world_mut(), fps_panel, false);
    let fps_content = super::panel_content(tree, fps_panel);
    let fps_label = tree.in_parent(fps_content, |tree| {
        tree.add_node()
            .size(100.pct(), (32.0).px())
            .with_text("0 fps", 24.0)
            .text_center()
            .color_raw::<UiBase>(vec4(0.0, 1.0, 0.0, 1.0))
            .entity()
    });

    OverlayHandles {
        fps_panel,
        fps_label,
    }
}

pub fn update(editor_world: &EditorWorld, world: &mut World) {
    let handles = &editor_world.resources.ui_handles;
    let fps_visible = editor_world.resources.ui.show_fps_label;
    ui_set_visible(world, handles.overlays.fps_panel, fps_visible);
    if fps_visible {
        let fps = world.resources.window.timing.frames_per_second;
        ui_set_text(
            world,
            handles.overlays.fps_label,
            &format!("{:.0} fps", fps),
        );
    }
}
