import theater.*;

import java.awt.event.KeyEvent;

import java.util.List;


/**
 * Uebernommen aus dem Greenfoot-Szenario asteroids.
 * <p>
 * </p>
 * A rocket that can be controlled by the arrowkeys: up, left, right. The gun is
 * fired by hitting the 'space' key.
 */
public class Rocket extends MovingThing {
    private TheaterImage rocket = new TheaterImage("rocket.png");
    private TheaterImage rocketWithThrust = new TheaterImage(
            "rocketWithThrust.png");

    /** The minimum delay between firing the gun. */
    private int minGunFireDelay = 5;

    /** How long ago we fired the gun the last time. */
    private int gunFireDelay = 0;

    /** How fast the rocket is */
    private Vector acceleration = new Vector(0, 0.3);

    public Rocket() {
        setImage(rocket);
    }

    public void run() {
        List<Component> comps = getStage()
                                    .getIntersectingComponents(this,
                Asteroid.class);

        if (comps.size() > 0) {
            Performance.getPerformance().playSound("MetalExplosion.wav");
            getStage().remove(this);
            Performance.getPerformance().stop();

            return;
        }

        gunFireDelay++;
        move();
    }

    /**
     * Should the rocket be ignited?
     */
    private void ignite(boolean b) {
        if (b) {
            setImage(rocketWithThrust);
            acceleration.setDirection(getRotation());
            increaseSpeed(acceleration);
        } else {
            setImage(rocket);
        }
    }

    /**
     * Fire a bullet if the gun is ready.
     */
    private void fire() {
        if (gunFireDelay >= minGunFireDelay) {
            Bullet b = new Bullet(getSpeed().copy(), getRotation());
            getStage().add(b, getColumn(), getRow());
            b.move();
            gunFireDelay = 0;
        }
    }

    public void keyPressed(KeyInfo info) {
        int code = info.getKeyCode();

        switch (code) {
        case KeyEvent.VK_UP:
            ignite(true);

            break;

        case KeyEvent.VK_LEFT:
            setRotation(getRotation() - 5);

            break;

        case KeyEvent.VK_RIGHT:
            setRotation(getRotation() + 5);

            break;

        case KeyEvent.VK_SPACE:
            fire();

            break;
        }
    }

    public void keyReleased(KeyInfo info) {
        int code = info.getKeyCode();

        switch (code) {
        case KeyEvent.VK_UP:
            ignite(false);

            break;
        }
    }
}
