package projectzombie.task;

import bdf.types.BdfNamedList;
import bdf.types.BdfObject;
import gl_engine.vec.Vec2i;
import gl_engine.vec.Vec3d;
import projectzombie.Main;
import projectzombie.entity.Entity;
import projectzombie.entity.player.EntityPlayer;
import projectzombie.util.TileState;
import projectzombie.world.chunk.ChunkEventHandler;
import projectzombie.world.layer.Layer;

public class TaskLadderDown extends Task
{
	private int layerID;
	private int step;

	public TaskLadderDown(Entity parent, BdfObject bdf) {
		super(parent, bdf);
	}
	
	public TaskLadderDown(Entity parent, int layerID) {
		super(parent);
		
		this.layerID = layerID;
		this.step = 0;
	}
	
	@Override
	public void BdfClassLoad(BdfObject bdf) {
		super.BdfClassLoad(bdf);
		
		BdfNamedList nl = bdf.getNamedList();
		
		layerID = nl.get("layerID").getInteger();
		step = nl.get("step").getInteger();
	}
	
	@Override
	public void BdfClassSave(BdfObject bdf) {
		super.BdfClassSave(bdf);
		
		BdfNamedList nl = bdf.getNamedList();
		
		nl.set("layerID", bdf.newObject().setInteger(layerID));
		nl.set("step", bdf.newObject().setInteger(step));
	}

	@Override
	public void update()
	{
		if(parent instanceof EntityPlayer)
		{
			EntityPlayer player = (EntityPlayer)parent;
			Vec3d pos = player.getPos();
			
			switch(step)
			{
			case 0:
				step = 1;
				player.setInAnimation(true);
				break;
			case 1:
				pos.y -= 0.02;
				if(pos.y < -1) {
					step = 2;
					pos.y = 8;
					Main.world.setLayer(layerID);
				}
				break;
			case 2:
				if(ChunkEventHandler.loaded)
				{
					step = 3;
					
					Vec2i tpos = pos.xz().toInt();
					
					Vec2i check_poses[] = {
							new Vec2i( 1,  0),
							new Vec2i(-1,  0),
							new Vec2i( 0,  1),
							new Vec2i( 0, -1),
					};
					
					// Set the first back tile to the tile the ladder is on
					Layer layer = Main.world.getLayer();
					TileState ets = layer.layergen.getTileDestroyed(layer, tpos);
					if(layer.getBackTile(tpos).tile != ets.tile) {
						layer.setBackTile(ets, tpos);
					}
					
					// Exit out of this branch if there is an empty space under the player
					else break;
					
					boolean found_exit = false;
					for(int i=1;!found_exit;i++)
					{
						for(Vec2i check_m_pos : check_poses)
						{
							Vec2i check_pos = check_m_pos.multiply(new Vec2i(i, i)).add(tpos);
							
							if(layer.getBackTile(check_pos).tile == ets.tile) {
								found_exit = true;
							}
							
							else {
								layer.setBackTile(new TileState(ets.tile, 0), check_pos);
							}
						}
					}
				}
				break;
			case 3:
				pos.y -= 0.04;
				if(pos.y <= 0) {
					step = 4;
					pos.y = 0;
					player.setInAnimation(false);
				}
				break;
			}
		}
	}

	@Override
	public boolean isDone() {
		return step == 4;
	}
	
}
