package rpgEngine.Logic.Game;

import java.awt.event.KeyEvent;
import rpgEngine.Data.Abstract.Game;
import rpgEngine.Data.Abstract.NPC.NPC;
import rpgEngine.Data.Abstract.NPC.Script;
import rpgEngine.Data.Abstract.NPC.ScriptPlayer;
import rpgEngine.Data.Abstract.World.Map;
import rpgEngine.Data.Abstract.World.MapCell;
import rpgEngine.Data.Raw.Graphics.CharacterSet;
import rpgEngine.UI.MainFrame;


public class PlayerNPCActivater {
	private NPC npc;
	private Game game;
	
	public PlayerNPCActivater(Game g) {
		game = g;
		npc = null;
	}
	
	public PlayerNPCActivater(Game g, NPC n) {
		npc = n;
		game = g;
	}
	
	
	public void findNPC() {
		Map map = game.getActiveMap();
		Integer position = CharacterSet.IMAGES_DOWN_0;
		Integer keyCode = 0;
		MapCell currentCell = null;
		MapCell destCell = null;
		int sx = 0;
		int sy = 0;
		int dx = 0;
		int dy = 0;
		
		Boolean varValue = false;
		Boolean varReq = false;
		Integer varID = -1;
		
		currentCell = map.findCharacter(game.getParty().get(0));
		position = game.getParty().get(0).getCharacterPosition();
		
		if((position == CharacterSet.IMAGES_DOWN_0) || (position == CharacterSet.IMAGES_DOWN_1) || (position == CharacterSet.IMAGES_DOWN_2)) {
			keyCode = KeyEvent.VK_DOWN;
		}
		else if((position == CharacterSet.IMAGES_LEFT_0) || (position == CharacterSet.IMAGES_LEFT_1) || (position == CharacterSet.IMAGES_LEFT_2)) {
			keyCode = KeyEvent.VK_LEFT;
		}
		else if((position == CharacterSet.IMAGES_RIGHT_0) || (position == CharacterSet.IMAGES_RIGHT_1) || (position == CharacterSet.IMAGES_RIGHT_2)) {
			keyCode = KeyEvent.VK_RIGHT;
		}
		else {
			keyCode = KeyEvent.VK_UP;
		}
		
		sx = currentCell.getX();
		sy = currentCell.getY();
		
		if(keyCode == KeyEvent.VK_UP) {
			dx = sx;
			dy = sy - 1;
		}
		else if(keyCode == KeyEvent.VK_DOWN) {
			dx = sx;
			dy = sy + 1;
		}
		else if(keyCode == KeyEvent.VK_LEFT) {
			dx = sx - 1;
			dy = sy;
		}
		else if(keyCode == KeyEvent.VK_RIGHT) {
			dx = sx + 1;
			dy = sy;
		}		
		
		try {
			destCell = game.getActiveMap().getRows().get(dy).get(dx);
		}
		catch(Exception e) {
			destCell = null;
		}
		
		if(destCell != null) {
			if(destCell.getNPC() != null) {
				npc = (NPC) destCell.getNPC();
				
				//test to see if npc is showable
				if(npc.getHasOnlyShowCriteria()) {
					varID = npc.getOnlyShowVariable();
					varReq = npc.getOnlyShowVariableValue();
					varValue = game.getVariable(varID);
					
					if(varValue != varReq) {
						npc = null;
					}
				}
			}
		}
	}
		
	
	public void activateNPC(MainFrame mf) {
		Script script = null;
		ScriptPlayer scriptPlayer = null;
		ScriptEventConsumer sec = null;
		
		if(npc == null) {
			return;
		}
		
		if(game == null) {
			return;
		}
		
		script = npc.getScript();
		
		scriptPlayer = new ScriptPlayer(script);
		
		game.setActiveScript(scriptPlayer);
		
		sec = new ScriptEventConsumer(game,mf);
		sec.consumeScriptItem();
	}
	
	
	
}
