import java.util.ArrayList;
import java.util.Random;

import processing.core.PApplet;
import processing.core.PImage;

public class ParticleSystem {

	Random generator;

	ArrayList particles; // An array list for all the particles
	Vector3D origin; // An origin point for where particles are birthed
	PImage[] imgs;
	PApplet parent;

	float randomXMovementOfOrigin = 50;
	float randomYMovementOfOrigin = 0;
	float randomZMovementOfOrigin = 0;
	

	
	ParticleSystem(PApplet parent, int num, Vector3D o, PImage[] imgs) {

		// seed the generator
		generator = new Random();

		// set the local vars
		this.parent = parent;
		this.imgs = imgs;

		// prep the particle holder
		particles = new ArrayList();
		
		// what is the origin?
		this.origin = o.copy();
		
		// add num particles initially
		for (int i = 0; i < num; i++) {
			particles.add(new Particle(parent, origin, imgs)); 
		}
	}

	// the cycling methond
	void step() {
		// Cycle through the ArrayList backwards b/c we are deleting
		for (int i = particles.size() - 1; i >= 0; i--) {
			Particle p = (Particle) particles.get(i);
			p.run(); // step each particle
			if (p.dead()) { 
				particles.remove(i); // kill dead particles
			}
		}
	}

	// Method to add a force vector to all particles currently in the system
	void add_force(Vector3D dir) {
		for (int i = particles.size() - 1; i >= 0; i--) {
			Particle p = (Particle) particles.get(i);
			p.add_force(dir);
		}

	}

	void addParticle() {
		
	
		// give it a little random movement
		
		float randX = parent.random(-randomXMovementOfOrigin,randomXMovementOfOrigin);
		float randY = parent.random(-randomYMovementOfOrigin,randomYMovementOfOrigin);
		float randZ = parent.random(-randomZMovementOfOrigin,randomZMovementOfOrigin);
		
		Vector3D randomVector = new Vector3D(randX,randY,randZ);
		Vector3D ooo = origin.copy();
		ooo.add(randomVector);
		
		particles.add(new Particle(parent, ooo, imgs));
	}

	void addParticle(Particle p) {
		particles.add(p);
	}

	// A method to test if the particle system still has particles
	boolean dead() {
		if (particles.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

}
