package rpgEngine.UI;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import rpgEngine.Data.Abstract.Game;
import rpgEngine.Logic.Camera.GameCamera;
import rpgEngine.Logic.Camera.GenericCamera;
import rpgEngine.Logic.Game.PlayerMover;
import rpgEngine.Logic.Game.PlayerNPCActivater;
import rpgEngine.Logic.Game.ScriptEventConsumer;


public class GamePanel extends GenericPanel {
	private static final long serialVersionUID = 6538729434640140830L;
	private GenericCamera camera;
	
	
	public GamePanel(Integer id, MainFrame p) {
		super(id, p);
		
		camera = new GameCamera(this);
	}
	
	
	@Override
	public void ProcessKeyEvent(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_DOWN) {
			processMoveKey(KeyEvent.VK_DOWN);
		}
		else if(e.getKeyCode() == KeyEvent.VK_UP) {
			processMoveKey(KeyEvent.VK_UP);
		}
		else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
			processMoveKey(KeyEvent.VK_LEFT);
		}
		else if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
			processMoveKey(KeyEvent.VK_RIGHT);
		}		
		else if(e.getKeyCode() == KeyEvent.VK_ENTER) {
			processActionKey();
		}
		else if(e.getKeyCode() == KeyEvent.VK_SPACE) {
			processActionKey();
		}
		else if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
			processEscapeKey();
		}
	}
	
	
	private void processMoveKey(Integer keyCode) {
		if(this.getParentMainFrame() == null) {
			return;
		}
		
		if(this.getParentMainFrame().getGame() == null) {
			return;
		}
		
		if(this.getParentMainFrame().getGame().getActiveScript() != null) {
			return;
		}
		
		PlayerMover pm = new PlayerMover(this.getParentMainFrame().getGame(), this.getParentMainFrame());
		pm.movePlayer(keyCode);
	}
	
	
	private void processActionKey() {
		Game game = null;
		PlayerNPCActivater pna = null;
		ScriptEventConsumer sec = null;
		
		if(this.getParentMainFrame() == null) {
			return;
		}
		
		if(this.getParentMainFrame().getGame() == null) {
			return;
		}
		
		game = this.getParentMainFrame().getGame();
		
		if(game.getActiveScript() == null) {
			//if no active script, try to activate npc if there is one
			pna = new PlayerNPCActivater(this.getParentMainFrame().getGame());
			pna.findNPC();
			pna.activateNPC(this.getParentMainFrame());
		}
		else {
			//process current script item
			sec = new ScriptEventConsumer(game,this.getParentMainFrame());
			sec.consumeScriptItem();
		}
	}
	
	
	private void processEscapeKey() {
		if(this.getParentMainFrame() == null) {
			return;
		}
		
		if(this.getParentMainFrame().getGame() == null) {
			return;
		}
		
		if(this.getParentMainFrame().getGame().getActiveScript() != null) {
			return;
		}
		
		this.getParentMainFrame().showScreen(MainFrame.PANEL_MENU_MAIN);
	}
	
	
	@Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
     
        BufferedImage img = camera.getImage();
        
        g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
    }


	
}
