package speiger.src.coreengine.rendering.models;

import java.util.List;
import java.util.Map;

import speiger.src.collections.objects.maps.impl.hash.Object2ObjectLinkedOpenHashMap;
import speiger.src.coreengine.assets.AssetLocation;
import speiger.src.coreengine.assets.AssetManager;
import speiger.src.coreengine.assets.reloader.IReloadableResource;
import speiger.src.coreengine.rendering.models.loader.MergedModelData;
import speiger.src.coreengine.rendering.models.loader.ModelLoader;
import speiger.src.coreengine.rendering.models.loader.SimpleModelData;

public class ModelCache implements IReloadableResource
{
	AssetManager manager;
	Map<AssetLocation, List<SimpleModelData>> models = new Object2ObjectLinkedOpenHashMap<>();
	
	public void setManager(AssetManager manager)
	{
		this.manager = manager;
	}
	
	@Override
	public void reload()
	{
		models.clear();
		load();
	}
	
	@Override
	public void destroy()
	{
		models.clear();
	}
	
	public void load()
	{
		for(AssetLocation model : manager.listAssets("models", this::isValidModel).keySet())
		{
			if(model.location().endsWith(".json")) addModel(model, ModelLoader.readModelData(model, manager));
			else if(model.location().endsWith(".spm")) addModel(model, ModelLoader.readLegacyModelData(model, manager));
		}
	}
	
	protected void addModel(AssetLocation location, List<SimpleModelData> data)
	{
		if(data.isEmpty())
		{
			System.out.println("["+location+"] Found Empty Model Data");
			return;
		}
		models.put(location, data);
	}
	
	protected boolean isValidModel(AssetLocation location)
	{
		String fileName = location.location();
		return fileName.endsWith(".json") || fileName.endsWith(".spm");
	}
	
	public SimpleModelData getModel(AssetLocation location)
	{
		List<SimpleModelData> data = models.get(location);
		return data == null ? null : data.get(0);
	}
	
	public List<SimpleModelData> getModels(AssetLocation location)
	{
		return models.get(location);
	}
	
	public MergedModelData getMergedModel(AssetLocation location)
	{
		return getMergedModel(location, "MergedModel");
	}
	
	public MergedModelData getMergedModel(AssetLocation location, String newName)
	{
		List<SimpleModelData> data = models.get(location);
		return data == null ? null : MergedModelData.merge(newName, data);
	}
}
