package projectzombie.entity;

import bdf.types.BdfArray;
import bdf.types.BdfNamedList;
import bdf.types.BdfObject;
import gl_engine.vec.Vec3d;
import projectzombie.init.Models;
import projectzombie.model.Model;
import projectzombie.world.chunk.Chunk;
import projectzombie.world.layer.Layer;

public class EntityContainer extends Entity implements EntityHoldsEntities
{
	private Entity[] entities;
	
	public EntityContainer(BdfObject bdf) {
		BdfClassLoad(bdf);
	}
	
	public EntityContainer(Vec3d pos, Vec3d velocity, Entity[] entities) {
		super(pos, velocity);
		
		this.entities = entities;
	}
	
	@Override
	public Model getModel() {
		return Models.EMPTY;
	}
	
	@Override
	public Entity[] getEntities() {
		return this.entities;
	}
	
	@Override
	public void tick(Chunk chunk, Layer layer) {
		super.tick(chunk, layer);
		
		int dead = 0;
		
		for(Entity entity : entities)
		{
			if(entity == null || entity.isDead()) {
				dead += 1;
				continue;
			}
			
			entity.tick(chunk, layer);
		}
		
		if(dead == entities.length - 1) {
			kill();
		}
	}
	
	@Override
	public void BdfClassLoad(BdfObject bdf) {
		super.BdfClassLoad(bdf);
		
		BdfNamedList nl = bdf.getNamedList();
		BdfArray array = nl.get("entities").getArray();
		
		entities = new Entity[array.size()];
		
		for(int i=0;i<entities.length;i++)
		{
			Entity entity = Entity.loadEntity(array.get(i));
			if(entity != null) {
				entities[i] = entity;
			}
		}
	}
	
	@Override
	public void BdfClassSave(BdfObject bdf) {
		super.BdfClassSave(bdf);
		
		BdfNamedList nl = bdf.getNamedList();
		BdfArray array = bdf.newArray();
		
		nl.set("entities", bdf.newObject().setArray(array));
		
		for(int i=0;i<entities.length;i++)
		{
			Entity e = entities[i];
			
			if(e == null || e.getID() == -1) {
				continue;
			}
			
			BdfObject e_bdf = bdf.newObject();
			e.BdfClassSave(e_bdf);
			
			array.add(e_bdf);
		}
	}
}
