package spaceObject.projectile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import javafx.geometry.Point2D;
import javafx.scene.image.Image;
import spaceObject.SpaceObject;
import spaceObject.spaceShip.SpaceShip;

public class Projectile extends SpaceObject {

	public static final String KEY_BLUE = "blue", KEY_RED = "red";
	public static final ArrayList<Projectile> projectiles = new ArrayList<Projectile>();

	private SpaceShip _spaceShip;
	private Point2D _movePoint2d = new Point2D(0, 0);
	private double _speed = 100, _liveTime = 5;

	public Projectile(String file, SpaceShip spaceShip, double speed, Point2D target) throws FileNotFoundException {
		super(projectiles, spaceShip.getGroup());

		setImage(new Image(new FileInputStream(file)));
		setFitHeight(5);
		setFitWidth(5);
		setX(spaceShip.getX() + spaceShip.getFitWidth() / 2);
		setY(spaceShip.getY() + spaceShip.getFitHeight() / 2);

		_spaceShip = spaceShip;
		_speed = speed;
		_movePoint2d = target;
	}

	@Override
	public void update(double deltaT) {
		for (int i = 0; i < _spaceShip.getTargets().size(); i++) {
			if (isInRange(_spaceShip.getTargets().get(i))) {
				_spaceShip.getTargets().get(i).setHitPoints(_spaceShip.getTargets().get(i).getHitPoints() - 1);
				if (_spaceShip.getTargets().get(i).getHitPoints() <= 0) {
					_spaceShip.setPoints(_spaceShip.getPoints() + _spaceShip.getTargets().get(i).getPoints());
					_spaceShip.getTargets().get(i).remove();
				}
				remove();
			}
		}

		setX(getX() + deltaT * _speed * _movePoint2d.getX());
		setY(getY() + deltaT * _speed * _movePoint2d.getY());

		_liveTime -= deltaT;
		if (_liveTime <= 0) {
			remove();
		}
	}

	public static void updateProjectiles(double deltaT) {
		for (int i = 0; i < projectiles.size(); i++) {
			projectiles.get(i).update(deltaT);
		}
	}

	private boolean isInRange(SpaceShip target) {
		if (getX() + 10 >= target.getX() && getY() + 10 >= target.getY()) {
			if (getX() - 10 <= target.getX() + target.getFitWidth()
					&& getY() - 10 <= target.getY() + target.getFitHeight()) {

				return true;
			}
		}
		return false;
	}
}
