use crate::app_context::AppContext;
use crate::engine_editor::spawn_asset_at_viewport;
use nightshade::prelude::*;

pub fn handle_asset_drop(
    context: &mut AppContext,
    mosaic: &crate::EditorMosaic,
    world: &mut World,
    ui_context: &egui::Context,
) {
    if !ui_context.input(|i| i.pointer.any_released()) {
        return;
    }

    let dragged_path: Option<std::path::PathBuf> =
        ui_context.data(|data| data.get_temp(egui::Id::new("dragged_asset_path")));

    if let Some(path) = dragged_path {
        ui_context.data_mut(|data| {
            data.remove::<std::path::PathBuf>(egui::Id::new("dragged_asset_path"));
        });

        if let Some(pointer_pos) = ui_context.pointer_hover_pos() {
            let is_over_viewport = mosaic
                .viewport_rects()
                .values()
                .any(|rect| rect.contains(pointer_pos));

            if is_over_viewport {
                context.ui.tree_dirty |= spawn_asset_at_viewport(&mut context.editor, world, &path);
            }
        }
    }
}
