package ecs.systems;

import ecs.components.*;
import ecs.core.Entity;
import ecs.core.System;
import entities.ExplosionEntity;
import res.display.FrameBuffer;
import res.geom.Vector2;

using Std;
using res.graphics.Painter;

class BombSystem extends System {
	public function new() {
		super(Bomb, TriggerRadius, Spatial);
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final triggerRadius = entity.get(TriggerRadius);
		final spatial = entity.get(Spatial);
		final targets = engine.queryEntities([TriggerRadius, Hostile, Spatial]);

		for (target in targets) {
			final targetTriggerRadius = target.get(TriggerRadius);
			final targetSpatial = target.get(Spatial);

			if (Vector2.xy(spatial.x - targetSpatial.x, spatial.y - targetSpatial.y)
				.length2() <= Math.pow(triggerRadius.radius + targetTriggerRadius.radius, 2)) {
				engine.add(new ExplosionEntity(spatial.x, spatial.y, triggerRadius.radius));

				target.get(Health).hit(1000);

				engine.remove(entity);
			}
		}
	}

	override function render(frameBuffer:FrameBuffer) {
		for (entity in entities) {
			final spatial = entity.get(Spatial);
			final triggerRadius = entity.get(TriggerRadius);

			frameBuffer.circle(spatial.x.int(), spatial.y.int(), triggerRadius.radius.int(), 2);
		}
	}
}
