import theater.*;


/**
 * Uebernommen aus dem Greenfoot-Szenario asteroids.
 * <p>
 * </p>
 * A rock in space
 */
public class Asteroid extends MovingThing {
    /** Size of this asteroid */
    private int size;

    /** Whether is is exploded */
    private boolean exploded = false;

    /** When the health reaches 0 the asteroid will explode */
    private int health;

    public Asteroid() {
        this(64);
    }

    public Asteroid(int size) {
        super(new Vector(new java.util.Random().nextInt(360), 2));
        setImage("rock.gif");
        setSize(size);
    }

    public Asteroid(int size, Vector speed) {
        super(speed);
        setImage("rock.gif");
        setSize(size);
    }

    public void run() {
        if (exploded) {
            return;
        }

        move();
    }

    public void setSize(int size) {
        health = size;
        this.size = size;

        TheaterImage image = new TheaterImage("rock.gif");
        image.scale(size, size);
        setImage(image);
    }

    /**
     * Explodes this asteroid into two smaller asteroids
     */
    private void explode() {
        if (exploded) {
            return;
        }

        exploded = true;

        Performance.getPerformance().playSound("Explosion.wav");

        if (size <= 16) {
            getStage().remove(this);

            return;
        }

        int r = getSpeed().getDirection() + new java.util.Random().nextInt(45);
        double l = getSpeed().getLength();
        Vector speed1 = new Vector(r + 90, l * 1.2);
        Vector speed2 = new Vector(r - 90, l * 1.2);
        Asteroid a1 = new Asteroid(size / 2, speed1);
        Asteroid a2 = new Asteroid(size / 2, speed2);
        getStage().add(a1, getColumn(), getRow());
        getStage().add(a2, getColumn(), getRow());
        a1.move();
        a2.move();

        getStage().remove(this);
    }

    /**
     * Hit this asteroid dealing the given amount of damage.
     */
    public void hit(int damage) {
        if (exploded) {
            return;
        }

        health = health - damage;

        if (health <= 0) {
            explode();
        }
    }
}
