package ecs.systems;

import ecs.components.*;
import ecs.core.Entity;
import ecs.core.System;
import res.geom.Vector2;

class FireGunSystem extends System {
	public function new() {
		super(Spatial, Aim, FireGun);
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final aim = entity.get(Aim);
		final fireGun = entity.get(FireGun);

		if (aim.targets.length > 0) {
			if (fireGun.delay <= 0) {
				final target = aim.targets[Math.floor(aim.targets.length * Math.random())];

				final spatial = entity.get(Spatial);
				final targetSpatial = target.get(Spatial);

				var v = Vector2.xy(targetSpatial.x - spatial.x, targetSpatial.y - spatial.y).normalize(100);

				final fireBall = new Entity('fireBall');

				fireBall.add(spatial.clone());
				fireBall.add(new Velocity(v.x, v.y));
				fireBall.add(new FireBall());
				fireBall.add(new Ttl(1));
				fireBall.add(new CollisionCircle(0));
				fireBall.add(new CollisionResult());
				fireBall.add(new Emitter(0.1, 4, 3, 1, [4, 5]));
				fireBall.add(new Acceleration(-20));

				engine.add(fireBall);

				fireGun.delay += fireGun.totalDelay;
			} else {
				fireGun.delay -= dt;
			}
		}
	}
}
