package scene;

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

import javafx.animation.AnimationTimer;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.control.Label;
import level.FinalLevel;
import level.Level;
import level.SecondLevel;
import level.StartLevel;
import level.ThirdLevel;
import spaceObject.projectile.Projectile;
import spaceObject.spaceShip.SpaceShip;
import spaceObject.spaceShip.Enemy;
import spaceObject.spaceShip.Allied;

public class GameUpdater extends AnimationTimer {

	private ArrayList<Level> _levels = new ArrayList<Level>();
	private Allied _ship;
	private Label _textbox = new Label("loading ...");
	private final long[] _frameTimes = new long[100];
	private int _frameTimeIndex = 0, _levelCount = 0;
	private boolean _arrayFilled = false;

	public GameUpdater(Group group, Allied ship) throws FileNotFoundException {
		start();

		_ship = ship;

		group.getChildren().add(_textbox);

		_levels.add(new StartLevel(group));
		_levels.add(new SecondLevel(group));
		_levels.add(new ThirdLevel(group));
		_levels.add(new FinalLevel(group));
	}

	@Override
	public void handle(long now) {
		long oldFrameTime = _frameTimes[_frameTimeIndex];
		_frameTimes[_frameTimeIndex] = now;
		_frameTimeIndex = (_frameTimeIndex + 1) % _frameTimes.length;
		if (_frameTimeIndex == 0) {
			_arrayFilled = true;
		}
		if (_arrayFilled) {
			long elapsedNanos = now - oldFrameTime;
			long elapsedNanosPerFrame = elapsedNanos / _frameTimes.length;
			double frameRate = 1_000_000_000 / elapsedNanosPerFrame;
			double deltaT = frameRate / 10_000;

			_textbox.setText(new String("live:\t\t" + _ship.getHitPoints() + "\nscore:\t" + _ship.getPoints()));

			// Update frames
			for (int i = 0; i < Allied.player.size(); i++) {
				Allied.player.get(i).update(deltaT);
			}
			for (SpaceShip spaceShip : Enemy.opponent) {
				spaceShip.update(deltaT);
			}
			Projectile.updateProjectiles(deltaT);
			if (Allied.player.isEmpty()) {
				stop();
				System.err.print("Game Over");
			}
			if (Enemy.opponent.isEmpty()) {
				if (_levelCount < _levels.size()) {
					try {
						_levels.get(_levelCount).spawnShips();
						_levelCount++;
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				} else {
					stop();
					System.err.println("You Win");
				}
			}
		}
	}
}
