/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Game;

import java.awt.Point;
import javaPlay.GameEngine;
import javaPlay.Keyboard;

/**
 *
 * @author Jose Ricardo
 */
public class Player extends RenderableGameEntitie {

    private float fire_current_delay = 0;


    @Override
    public void step(long timeElapsed) {
        Keyboard k = GameEngine.getInstance().getKeyboard();
        Point delta = new Point(0, 0);

        if (k.keyDown(Keyboard.UP_KEY))
            delta.y = -Globals.PLAYER_SPEED;
        else if (k.keyDown(Keyboard.DOWN_KEY))
            delta.y = Globals.PLAYER_SPEED;

        if (k.keyDown(Keyboard.LEFT_KEY))
            delta.x = -Globals.PLAYER_SPEED;
        else if (k.keyDown(Keyboard.RIGHT_KEY))
            delta.x = Globals.PLAYER_SPEED;

        x += delta.x;
        y += delta.y;

        // Verificar se ultrapassou os limites da tela
        if (x + width >= Globals.VIEWPORT_WIDTH) x = Globals.VIEWPORT_WIDTH - width;
        else if (x < 0) x = 0;

        if (y + height >= Globals.VIEWPORT_HEIGHT) y = Globals.VIEWPORT_HEIGHT - height;
        else if (y < 0) y = 0;

        // Verificar se o jogador deseja atirar
        if (k.keyDown(Keyboard.SPACE_KEY)){
            // Verificar o tempo desde o último tiro
            if (fire_current_delay <= 0){
                PlayerBullet bullet = new PlayerBullet();
                bullet.setSprite("data/playerbullet.png", 32, 32);
                bullet.x = x + (width / 2) - 15;
                bullet.y = y - (height / 2) + 10;
                Scene.getInstance().addGameObject(bullet);
                fire_current_delay = Globals.FIRE_TIME_DELAY;
            }
        }

        // Atualizar o tempo de tiro
        if (fire_current_delay > 0) fire_current_delay -= Globals.TIME_PER_FRAME;

        // Verificar colisão com inimigos
        Object[] items = Scene.getInstance().getObjects();
        for (int i = 0; i < items.length; i++){
            RenderableGameEntitie rge = (RenderableGameEntitie) items[i];
            if (rge.tag.equals("Enemy"))
                if (Scene.collide(this, rge))
                    // Se colidiu, termina o jogo e volta ao menu inicial
                    GameEngine.getInstance().setNextGameStateController(
                            Globals.SCREEN_MENU);
        }
    }

}
