package speiger.src.coreengine.utils.collections.registries.flat;

import speiger.src.coreengine.assets.AssetLocation;
import speiger.src.coreengine.utils.collections.registries.simple.SimpleRegistryWithDefault;

public class FlatRegistry<T extends IFlatRegistryEntry<T>>extends SimpleRegistryWithDefault<T> {
	int usedCapacity = 0;
	IFlatRegistryEntry<T>[] flatIds;
	
	public FlatRegistry(int capacity, AssetLocation defaultValue) {
		super(capacity, defaultValue);
	}
	
	@Override
	public T register(T value) {
		int meta = value.getMetadata() + 1;
		if(meta >= capacity - usedCapacity) throw new RuntimeException("Registry Is Overflowed");
		T result = super.register(value);
		usedCapacity += meta;
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public void bake() {
		freeze();
		flatIds = new IFlatRegistryEntry[usedCapacity];
		int index = 0;
		for(T entry : this) {
			entry.setFlatId(index);
			int meta = entry.getMetadata();
			for(int i = 0;i <= meta;i++) {
				flatIds[index + i] = entry;
			}
			index += meta + 1;
		}
	}
	
	@SuppressWarnings("unchecked")
	public T getFromFlatId(int id) { return (T)flatIds[id]; }
	public int getMetadata(int id) { return id - flatIds[id].getFlatId(); }
	public int flatSize() { return flatIds.length; }
}
