package projectzombie.tiles;

import java.util.Random;

import gl_engine.MathHelpers;
import gl_engine.vec.Vec2i;
import gl_engine.vec.Vec3d;
import mainloop.task.IMainloopTask;
import projectzombie.Main;
import projectzombie.entity.Entity;
import projectzombie.entity.particle.ParticleBreak;
import projectzombie.entity.player.EntityPlayer;
import projectzombie.init.LayerGenerators;
import projectzombie.init.Models;
import projectzombie.model.Model;
import projectzombie.util.TileState;
import projectzombie.world.chunk.ChunkEventHandler;
import projectzombie.world.layer.Layer;
import projectzombie.world.layer.layergen.LayerGenBossArena;

public class TileBossPortal extends Tile
{
	private static Random rand = new Random();

	public TileBossPortal() {
		
		this.emitsLight = true;
		this.tileHitbox = 0.4;
		this.tileSolid = true;
		this.unbreakable = true;
	}
	
	@Override
	public double getLightLevel(TileState state, Vec2i pos) {
		return 0.6;
	}
	
	@Override
	public boolean onActivated(Layer layer, Vec2i tpos, Entity entity, TileState state) {
		super.onActivated(layer, tpos, entity, state);
		
		if(entity instanceof EntityPlayer)
		{
			// Get the player and set some player variables
			EntityPlayer ep = (EntityPlayer)entity;
			ep.getPos().y = 5;
			
			// Create the boss arena
			LayerGenBossArena layergen = (LayerGenBossArena) LayerGenerators.BOSS_ARENA;
			layergen.spawnPlayer(ep);
			layer.setFrontTile(TileState.EMPTY, tpos);
			layer.spawnEntity(new ParticleBreak(tpos.toDouble().xny(), new Vec3d(0, 0, 0), getModel(state.meta)));
			
			int id = Main.world.addLayer(new Layer(rand, layergen));
			Main.world.setLayer(id);
			
			// Do the arena falling animation
			Main.mainloop.register(new IMainloopTask()
			{
				int stage = 0;
				double velocity = 0;
				
				@Override
				public void MainLoopUpdate()
				{
					if(stage == 0)
					{
						// Only do this if the world is loaded
						if(ChunkEventHandler.loaded)
						{
							this.velocity -= MathHelpers.FallSpeed;
							ep.getPos().y += this.velocity;
							if(ep.getPos().y <= 0) {
								this.velocity *= -0.6;
								if(this.velocity <= 0.001) {
									ep.getPos().y = 0;
								}
							}
						}
					}
				}
				
				@Override
				public boolean MainLoopRepeat() {
					return ep.getPos().y > 0 || this.velocity > 0.001;
				}
				
				@Override
				public boolean MainLoopDelay(long millis) {
					return millis > 10;
				}
			});
		}
		
		return true;
	}

	@Override
	public Model getModel(byte meta) {
		return Models.TILE_BOSS_PORTAL;
	}

}
