package ecs.systems;

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

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

	override function update(dt:Float) {
		final orbitSystem = engine.getSystem(OrbitSystem);
		final economicsSystem = engine.getSystem(EconomicsSystem);
		final earth = engine.getByName('earth')[0];

		final earthRadius = earth.get(TriggerRadius);

		for (entity in entities) {
			final ore = entity.get(Ore);
			final spatial = entity.get(Spatial);

			if (ore.magneting) {
				if (Vector2.xy(orbitSystem.centerX - spatial.x, orbitSystem.centerY - spatial.y).length2() < Math.pow(earthRadius.radius, 2)) {
					engine.remove(entity);

					economicsSystem.collect(ore.value);
					engine.add(Entity.of(new Audio('coin')));
				}
			} else {
				final velocity = entity.get(Velocity);

				if (velocity.speed == 0) {
					ore.magneting = true;

					entity.remove(entity.get(Acceleration));
					entity.remove(entity.get(CollisionCircle));

					final v = Vector2.xy(orbitSystem.centerX - spatial.x, orbitSystem.centerY - spatial.y).normalize(1);

					velocity.x = v.x;
					velocity.y = v.y;

					entity.add(new Acceleration(30));
				}
			}
		}
	}
}
