#[cfg(not(target_arch = "wasm32"))]
use crate::engine_editor::undo::snapshot::{EntitySnapshot, recreate_entity};
#[cfg(not(target_arch = "wasm32"))]
use nightshade::ecs::transform::queries::query_children;
#[cfg(not(target_arch = "wasm32"))]
use nightshade::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use serde::{Deserialize, Serialize};

#[cfg(not(target_arch = "wasm32"))]
#[derive(Serialize, Deserialize)]
pub struct ClipboardData {
    pub version: String,
    pub hierarchies: Vec<ClipboardHierarchy>,
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Serialize, Deserialize, Clone)]
pub struct ClipboardHierarchy {
    #[serde(flatten)]
    pub snapshot: EntitySnapshot,
    pub children: Vec<ClipboardHierarchy>,
}

#[cfg(not(target_arch = "wasm32"))]
impl ClipboardHierarchy {
    pub fn from_world(world: &World, entity: Entity) -> Self {
        let mut snapshot = EntitySnapshot::capture(world, entity);
        snapshot.global_transform = None;
        snapshot.parent_entity = None;
        let children = query_children(world, entity)
            .into_iter()
            .map(|child| ClipboardHierarchy::from_world(world, child))
            .collect();

        ClipboardHierarchy { snapshot, children }
    }

    pub fn spawn(&self, world: &mut World, parent: Option<Entity>) -> Entity {
        let entity = recreate_entity(world, &self.snapshot, parent);

        for child in &self.children {
            child.spawn(world, Some(entity));
        }

        world.resources.children_cache_valid = false;
        entity
    }
}
