package ecs.systems;

import res.geom.Vector2;
import ecs.components.*;
import ase.FrameHeader;
import ase.Palette;
import ecs.core.Entity;
import ecs.core.System;
import res.rom.Rom;

class BombSpawnSystem extends System {
	var rom:Rom;

	var orbitSystem:OrbitSystem;

	public function new(rom:Rom) {
		super(BombSpawn, Orbiter);

		this.rom = rom;
	}

	override function updateEntity(entity:Entity, dt:Float) {
		if (orbitSystem == null)
			orbitSystem = engine.getSystem(OrbitSystem);

		final orbiter = entity.get(Orbiter);
		final bombSpawn = entity.get(BombSpawn);

		var spawn = false;

		if (bombSpawn.lastPhase == null) {
			spawn = true;
		} else {
			final cha = orbiter.phase - bombSpawn.lastPhase; // Math.min(bombSpawn.lastPhase - orbiter.phase, orbiter.phase - bombSpawn.lastPhase);
			final dist = (cha / (Math.PI * 2)) * (2 * Math.PI * orbiter.rX);

			if (dist >= bombSpawn.distance)
				spawn = true;
		}

		if (spawn) {
			final x = orbitSystem.centerX + Math.cos(orbiter.phase) * orbiter.rX;
			final y = orbitSystem.centerY + Math.sin(orbiter.phase) * orbiter.rY;

			for (prev in bombSpawn.spawned) {
				if (engine.inEngine(prev)) {
					final sSpatial = prev.get(Spatial);
					final sTriggerRadius = prev.get(TriggerRadius);

					if (Vector2.xy(x - sSpatial.x, y - sSpatial.y).length2() < Math.pow(sTriggerRadius.radius + 15, 2)) {
						return;
					}
				} else {
					bombSpawn.spawned.remove(prev);
				}
			}

			bombSpawn.lastPhase = orbiter.phase;

			final bomb = new Entity('bomb');
			bomb.add(new Bomb());
			bomb.add(new Spatial(x, y));
			bomb.add(new Sprite(rom.sprites['bomb'], 0.5, 0.5));
			bomb.add(new TriggerRadius(15));
			engine.add(bomb);

			bombSpawn.spawned.push(bomb);
		}
	}
}
