package ecs.systems;

import Math.*;
import ecs.components.Death;
import ecs.components.Health;
import ecs.components.Impact;
import ecs.components.Spatial;
import ecs.components.TriggerRadius;
import ecs.core.System;
import res.geom.Vector2;

class ImpactSystem extends System {
	public function new() {
		super(Impact, Spatial, TriggerRadius);
	}

	override function update(dt:Float) {
		final earth = engine.getByName('earth')[0];
		final shakeSystem = engine.getSystem(ShakeSystem);
		final flashSystem = engine.getSystem(FlashSystem);

		if (earth != null) {
			final earthTriggerRadius = earth.get(TriggerRadius);
			final earthSpatial = earth.get(Spatial);
			final earthHealth = earth.get(Health);

			for (entity in entities) {
				final triggerRadius = entity.get(TriggerRadius);
				final spatial = entity.get(Spatial);
				final impact = entity.get(Impact);

				if (Vector2.xy(spatial.x - earthSpatial.x, spatial.y - earthSpatial.y).length2() <= pow(earthTriggerRadius.radius + triggerRadius.radius, 2)) {
					earthHealth.hit(impact.hitPower);
					entity.add(new Death());
					shakeSystem.shake(10, 2);
					flashSystem.flash(1, 0.05, 14);
				}
			}
		}
	}
}
