package ecs.systems;

import ecs.components.Acceleration;
import ecs.components.Spatial;
import ecs.components.Velocity;
import ecs.components.VelocityChange;
import ecs.core.Entity;
import ecs.core.System;
import res.geom.Vector2;

class MoverSystem extends System {
	public function new() {
		super(Spatial, Velocity);
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final spatial = entity.get(Spatial);
		final velocity = entity.get(Velocity);

		final velocityChange = entity.get(VelocityChange);

		if (velocityChange != null) {
			if (velocityChange.timePassed <= velocityChange.time) {
				final v = velocityChange.fromVelocity
					+ (velocityChange.toVelocity - velocityChange.fromVelocity) * (velocityChange.timePassed / velocityChange.time);

				final vec = Vector2.xy(velocity.x, velocity.y).normalize(v);

				velocity.x = vec.x;
				velocity.y = vec.y;

				velocityChange.timePassed += dt;
			}
		}

		final acceleration = entity.get(Acceleration);

		if (acceleration != null)
			velocity.speed = Math.max(0, velocity.speed + acceleration.value * dt);

		spatial.x += velocity.x * dt;
		spatial.y += velocity.y * dt;
	}
}
