package projectzombie.entity;

import bdf.types.BdfNamedList;
import bdf.types.BdfObject;
import gl_engine.MathHelpers;
import gl_engine.vec.Vec2d;
import gl_engine.vec.Vec3d;
import projectzombie.entity.particle.ParticleSmokeTrail;
import projectzombie.init.Models;
import projectzombie.model.Model;
import projectzombie.world.chunk.Chunk;
import projectzombie.world.layer.Layer;

public class EntityTnt extends Entity implements EntityHoldsEntities
{
	protected boolean active = true;
	protected int explode_time;
	private int explode_radius;
	private double explode_damage;
	private ParticleSmokeTrail smoke_particles;
	
	@Override
	public Entity[] getEntities() {
		return new Entity[] {smoke_particles};
	}
	
	public EntityTnt(BdfObject bdf) {
		smoke_particles = new ParticleSmokeTrail(this);
		BdfClassLoad(bdf);
	}
	
	@Override
	public void BdfClassLoad(BdfObject bdf) {
		super.BdfClassLoad(bdf);
		
		BdfNamedList nl = bdf.getNamedList();
		BdfNamedList explode = nl.get("explosion").getNamedList();
		explode_time = explode.get("time").getInteger();
		explode_radius = explode.get("radius").getInteger();
		explode_damage = explode.get("damage").getDouble();
	}
	
	@Override
	public void BdfClassSave(BdfObject bdf) {
		super.BdfClassSave(bdf);
		
		BdfNamedList nl = bdf.getNamedList();
		BdfNamedList explode = nl.get("explosion").getNamedList();
		explode.set("time", bdf.newObject().setInteger(explode_time));
		explode.set("radius", bdf.newObject().setInteger(explode_radius));
		explode.set("damage", bdf.newObject().setDouble(explode_damage));
	}
	
	public EntityTnt(Vec3d pos, Vec3d velocity, double angle, int explode_radius, double explode_damage) {
		super(pos, velocity.add(new Vec3d(0, 0.1, 0)));
		
		Vec2d v = MathHelpers.moveTowards2(0.05, Math.toRadians(angle));
		velocity = velocity.add(new Vec3d(v.x, v.y, 0.01));
		this.explode_radius = explode_radius;
		this.explode_damage = explode_damage;
		this.smoke_particles = new ParticleSmokeTrail(this);
		
		// Set to 2.5 seconds
		this.explode_time = 250;
	}
	
	protected void explode(Layer layer)
	{
		layer.spawnEntity(new EntityExplosion(getPos(), explode_radius, explode_damage));
	}
	
	@Override
	public void tick(Chunk chunk, Layer layer) {
		super.tick(chunk, layer);
		
		smoke_particles.tick(chunk, layer);
		
		if(!active)
		{
			if(smoke_particles.noMoreParticles()) {
				kill();
			}
			
			return;
		}
		
		// Explode if it is time for the tnt to blow up
		explode_time -= 1;
		if(explode_time < 0) {
			smoke_particles.stopParticles();
			active = false;
			explode(layer);
		}
	}
	
	@Override
	protected void moveAwayFromSolidEntities(Layer layer) {
	}

	@Override
	public Model getModel() {
		return active ? Models.ENTITY_TNT : null;
	}
	
}
