//! Editor-owned live Material and Material Instance values.

use std::collections::HashMap;

use bevy::prelude::Resource;
use shared::{MaterialAsset, MaterialInstanceAsset, MaterialRef};

#[derive(Debug, Clone)]
pub enum LiveMaterialDocument {
    Material(MaterialAsset),
    Instance(MaterialInstanceAsset),
}

#[derive(Debug, Clone)]
pub struct LiveMaterialDocumentEntry {
    pub revision: u64,
    pub document: LiveMaterialDocument,
}

#[derive(Resource, Default, Debug)]
pub struct LiveMaterialDocumentOverlay {
    documents: HashMap<String, LiveMaterialDocumentEntry>,
}

impl LiveMaterialDocumentOverlay {
    pub fn update_material(
        &mut self,
        asset_id: impl Into<String>,
        revision: u64,
        asset: MaterialAsset,
    ) {
        self.documents.insert(
            asset_id.into(),
            LiveMaterialDocumentEntry {
                revision,
                document: LiveMaterialDocument::Material(asset),
            },
        );
    }

    pub fn update_instance(
        &mut self,
        asset_id: impl Into<String>,
        revision: u64,
        instance: MaterialInstanceAsset,
    ) {
        self.documents.insert(
            asset_id.into(),
            LiveMaterialDocumentEntry {
                revision,
                document: LiveMaterialDocument::Instance(instance),
            },
        );
    }

    pub fn remove(&mut self, asset_id: &str) {
        self.documents.remove(asset_id);
    }

    pub fn revision_for_asset(&self, asset_id: &str) -> Option<u64> {
        self.documents.get(asset_id).map(|entry| entry.revision)
    }

    pub(crate) fn get(&self, reference: &MaterialRef) -> Option<&LiveMaterialDocumentEntry> {
        self.documents.get(&reference.0.asset_id)
    }
}
