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

pub fn set_primary(editor_world: &mut EditorWorld, entity: Option<Entity>) {
    editor_world.resources.ui.selected_entity = entity;
    editor_world.resources.ui.selected_entities = match entity {
        Some(entity) => vec![entity],
        None => Vec::new(),
    };
    editor_world.resources.ui_handles.inspector.dirty = true;
}

pub fn set_many(editor_world: &mut EditorWorld, entities: Vec<Entity>) {
    editor_world.resources.ui.selected_entity = entities.last().copied();
    editor_world.resources.ui.selected_entities = entities;
    editor_world.resources.ui_handles.inspector.dirty = true;
}

pub fn clear(editor_world: &mut EditorWorld) {
    editor_world.resources.ui.selected_entity = None;
    editor_world.resources.ui.selected_entities.clear();
    editor_world.resources.ui_handles.inspector.dirty = true;
}

pub fn toggle(editor_world: &mut EditorWorld, entity: Entity) {
    let position = editor_world
        .resources
        .ui
        .selected_entities
        .iter()
        .position(|existing| *existing == entity);
    match position {
        Some(index) => {
            editor_world.resources.ui.selected_entities.remove(index);
            let new_primary = editor_world.resources.ui.selected_entities.last().copied();
            editor_world.resources.ui.selected_entity = new_primary;
        }
        None => {
            editor_world.resources.ui.selected_entities.push(entity);
            editor_world.resources.ui.selected_entity = Some(entity);
        }
    }
    editor_world.resources.ui_handles.inspector.dirty = true;
}

pub fn remove(editor_world: &mut EditorWorld, entity: Entity) {
    editor_world
        .resources
        .ui
        .selected_entities
        .retain(|existing| *existing != entity);
    if editor_world.resources.ui.selected_entity == Some(entity) {
        editor_world.resources.ui.selected_entity =
            editor_world.resources.ui.selected_entities.last().copied();
    }
    editor_world.resources.ui_handles.inspector.dirty = true;
}

pub fn sync_to_engine(editor_world: &EditorWorld, world: &mut World) {
    world
        .resources
        .editor_selection
        .bounding_volume_selected_entity = editor_world.resources.ui.selected_entity;
    let primary = editor_world.resources.ui.selected_entity;
    world.resources.editor_selection.selected_entities = editor_world
        .resources
        .ui
        .selected_entities
        .iter()
        .copied()
        .filter(|entity| Some(*entity) != primary)
        .collect();
}
