package de.rico.adventure.actions.custom;

import javax.media.opengl.GL;

import de.rico.adventure.actions.AbstractAction;
import de.rico.adventure.actions.ActionScheduler;
import de.rico.adventure.entity.character.PlayableCharacter;
import de.rico.adventure.script.trigger.AbstractTrigger;
import de.rico.adventure.structure.EntryPoint;
import de.rico.adventure.structure.Room;
import de.rico.engine.camera.Camera;

/**
 * This game action can be used to let the player character
 * exit the current room and enter another one.
 * @author Frank Bruns
 *
 */
public class EnterRoom extends AbstractAction
{
	private String entryPointId = null;
	private Room room = null;
	private int camPerspId = 0;

	/**
	 * Creates a game action to let the player enter another room.
	 * @param player player object
	 * @param room room to enter
	 * @param entryPointId script id of the entry point to use for entering
	 * @param camPerspId id of the camera perspective to use initially
	 */
	public EnterRoom(PlayableCharacter player, Room room, String entryPointId, int camPerspId)
	{
		super(player);
		this.room = room;
		this.entryPointId = entryPointId;
		this.camPerspId = camPerspId;
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#update(long)
	 */
	@Override
	public void update(long elapsedTime)
	{
		PlayableCharacter player = (PlayableCharacter)this.getEntity();

		// remove player from the triggers of the old room
		// and make the removal valid
		for(AbstractTrigger trigger : player.getRoom().getTriggers())
		{
			trigger.removeCandidate(player);
			trigger.update(0);
		}


		// transfer player from current room to the next one
		player.getRoom().update(0);
		player.setPreviousRoom(player.getRoom());
		player.getRoom().removePlayer();

		this.room.setPlayer(player);

		// set character to entry point
		EntryPoint ep = this.room.getEntryPoint(this.entryPointId);
		this.getEntity().getMesh().setPosition(ep.getPosition());
		this.getEntity().getMesh().setRotation(ep.getRotation());

		// make new room active and finalize the changes
		this.room.getChapter().setActiveRoom(this.room.getScriptId());

		// register player to the triggers of the new room
		// and make the registration valid
		for(AbstractTrigger trigger : this.room.getTriggers())
		{
			trigger.addCandidate(player);
			trigger.update(0);
		}
		this.room.update(0L);

		Camera.getInstance().setToCameraPerspective(this.camPerspId);

		// remove game action afterwards
		ActionScheduler.getInstance().removeFirst();
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#draw(javax.media.opengl.GL)
	 */
	@Override
	public void draw(GL gl)
	{
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#finishUp()
	 */
	@Override
	public void finishUp()
	{
		// TODO Auto-generated method stub

	}
}
