use super::{ComponentInspector, EditorContext};
use nightshade::prelude::*;

pub struct MeshInspector;

const MESH_TYPES: &[&str] = &["Cube", "Sphere", "Plane", "Cylinder", "Cone", "Torus"];

impl ComponentInspector for MeshInspector {
    fn name(&self) -> &str {
        "Mesh"
    }

    fn has_component(&self, world: &World, entity: Entity) -> bool {
        world.entity_has_render_mesh(entity)
    }

    fn add_component(&self, world: &mut World, entity: Entity) {
        world.set_render_mesh(entity, RenderMesh::default());
    }

    fn remove_component(&self, world: &mut World, entity: Entity) {
        world.remove_render_mesh(entity);
    }

    fn ui(
        &mut self,
        world: &mut World,
        entity: Entity,
        ui: &mut egui::Ui,
        _editor: &mut EditorContext,
    ) {
        if let Some(mesh) = world.get_render_mesh_mut(entity) {
            ui.label("Mesh Type:");
            let display_name = truncate_mesh_name(&mesh.name, 30);
            egui::ComboBox::from_id_salt("mesh_type")
                .selected_text(&display_name)
                .show_ui(ui, |ui| {
                    for mesh_type in MESH_TYPES {
                        ui.selectable_value(&mut mesh.name, mesh_type.to_string(), *mesh_type);
                    }
                });
        }
    }
}

fn truncate_mesh_name(name: &str, max_len: usize) -> String {
    if let Some(filename) = std::path::Path::new(name).file_name() {
        let filename_str = filename.to_string_lossy();
        if filename_str.len() <= max_len {
            return filename_str.to_string();
        }
        return format!("{}...", &filename_str[..max_len.saturating_sub(3)]);
    }
    if name.len() <= max_len {
        return name.to_string();
    }
    format!("{}...", &name[..max_len.saturating_sub(3)])
}
