use crate::ecs::EditorWorld;
use crate::systems::retained_ui::{Action, UiHandles};
use nightshade::prelude::*;

#[derive(Default, Clone)]
pub struct EntityContextMenuHandles {
    pub menu: Entity,
}

pub fn build(tree: &mut UiTreeBuilder) -> EntityContextMenuHandles {
    let menu = tree.add_context_menu_from_builder(
        ContextMenuBuilder::new()
            .item("Frame", "")
            .item("Duplicate", "Ctrl+D")
            .item("Delete", "Del")
            .separator()
            .item("Convert similar to instanced", ""),
    );
    EntityContextMenuHandles { menu }
}

pub fn poll(editor_world: &mut EditorWorld, world: &mut World, handles: &UiHandles) {
    let menu = handles.entity_context_menu.menu;
    let mut item_clicks: Vec<usize> = Vec::new();
    for event in ui_events(world) {
        if let UiEvent::ContextMenuItemClicked {
            entity, item_index, ..
        } = event
            && *entity == menu
        {
            item_clicks.push(*item_index);
        }
    }
    for item_index in item_clicks {
        let action = match item_index {
            0 => Some(Action::FrameScene),
            1 => Some(Action::DuplicateSelectedEntity),
            2 => Some(Action::DeleteSelectedEntity),
            3 => Some(Action::ConvertSimilarToInstanced),
            _ => None,
        };
        if let Some(action) = action {
            editor_world.resources.ui_interaction.actions.push(action);
        }
    }
}
