import java.awt.Rectangle;
import java.util.Random;

public class Particle extends Entity {
	
	int tarX, tarY;
	Game game;
	Random r = new Random();
	int mode = 0;
	
	public Particle(String ref, Game game, int x, int y, boolean solid, int tarX, int tarY, int explosive) {
		super(ref, x, y, -1, 20, 10, 10, solid);
		
		this.game = game;
		
		if (tarX != -1) {
			this.tarX = tarX;
			this.tarY = tarY;
			mode = 1;
		} else {
			sprite = game.pm.blood[r.nextInt(game.pm.blood.length)];
			dx += r.nextInt(50*explosive) - 25*explosive;
			dy += r.nextInt(50*explosive) - 25*explosive;
		}
	}

	public void collidedWith(Entity other) {
		
		if (mode == 0 && other instanceof Block || other instanceof Piston) {
//			super.dy = 0;
			
			if (!customSize) {
				me.setBounds((int) x,(int) y, sprite.getWidth(), sprite.getHeight());
			} else {
				me.setBounds(rect.x, rect.y, (int) rect.getWidth(), (int) rect.getHeight());
			}
			if (!other.customSize) {
				him.setBounds((int) other.x, (int) other.y, other.sprite.getWidth(), other.sprite.getHeight());
			} else {
				him.setBounds(other.rect.x, other.rect.y, (int) other.rect.getWidth(), (int) other.rect.getHeight());
			}
			Rectangle intersection = me.intersection(him);
			
			if (intersection.getHeight() > intersection.getWidth()) { // horizontal collision
				if (intersection.x == him.x) { // collision from right
					super.x -= intersection.getWidth();
				} else { // collision from left
					super.x += intersection.getWidth();
				}
			} else { // vertical collision
				if (intersection.y == him.y) { // collision from below
					super.y -= intersection.getHeight();
				} else { // collision from above
					super.y += intersection.getHeight();
				}
			}
			
			super.dx = super.dx * Game.FRICTION;
			super.dy = super.dy * Game.FRICTION;
		}
	}
	
	public void move(long delta) {
		
		if (mode == 0) {
			
			dy += Game.GRAVITY;
			
		} else if (mode == 1) {
			double dirX = tarX - x;
			double dirY = tarY - y;
			
			double nDirX = Util.normaliseX(dirX, dirY);
			double nDirY = Util.normaliseY(dirX, dirY);
			
			if (Util.distBetween(x, y, tarX, tarY) > 10) {
				dx = delta * (nDirX * 50 + (r.nextInt(10) - 5));
				dy = delta * (nDirY * 50 + (r.nextInt(10) - 5));
			} else {
				game.removeEntity(this);
			}
		} else {
			
		}
		
		super.move(delta);
	}
	
}
