import theater.*;

import java.util.*;

/**
 * Übertragen aus dem Greenfoot-Szenario balloons
 * <p>
 * </p>
 * An explosion. It starts by expanding and then collapsing. The explosion will
 * explode other objects that the explosion intersects.
 */
public class Explosion extends Actor {
	/** How many images should be used in the animation of the explostion */
	private final static int IMAGE_COUNT = 8;

	/**
	 * The images in the explosion. This is static so the images are not
	 * recreated for every object (improves performance significantly).
	 */
	private static TheaterImage[] images;

	/** Current size of the explosion */
	private int size = 0;

	/** How much do we increment the index in the explosion animation. */
	private int increment = 1;

	public Explosion() {
         setPriority(1);
		initialiseImages();
		setImage(images[0]);
		Performance.getPerformance().playSound("explosion.wav");
	}

	/**
	 * Create the images for explosion.
	 */
	public synchronized static void initialiseImages() {
		if (images == null) {
			TheaterImage baseImage = new TheaterImage("explosion.png");
			int maxSize = baseImage.getWidth() * 8;
			int delta = maxSize / (IMAGE_COUNT + 1);
			int size = 0;
			images = new TheaterImage[IMAGE_COUNT];
			for (int i = 0; i < IMAGE_COUNT; i++) {
				size = size + delta;
				images[i] = new TheaterImage(baseImage);
				images[i].scale(size, size);
			}
		}
	}

	/**
	 * EXPLODE!
	 */
	public void run() {
		setImage(images[size]);

		size += increment;
		if (size >= IMAGE_COUNT) {
			increment = -increment;
			size += increment;
		}

		explodeOthers();
		if (size <= 0) {
			getStage().remove(this);
		}
	}

	/**
	 * Explodes all intersecting objects.
	 */
	private void explodeOthers() {
		List<Component> explodeEm = getStage().getIntersectingComponents(this,
				Balloon.class);
		for (Component a : explodeEm) {

			int x = a.getColumn();
			int y = a.getRow();
			// Replace other object with an explosion
			((Balloon) a).pop();

			// Enable for cascading explossions
			// getStage().add(new Explosion(), x, y);
		}
	}

}
