package ecs.systems;

import ecs.components.*;
import ecs.core.Entity;
import ecs.core.System;
import res.display.FrameBuffer;

using Std;
using res.graphics.Painter;

class FireBallSystem extends System {
	public function new() {
		super(Spatial, Ttl, CollisionCircle, CollisionResult, FireBall);
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final fireBall = entity.get(FireBall);
		final collisionCircle = entity.get(CollisionCircle);
		final collisionResult = entity.get(CollisionResult);
		final ttl = entity.get(Ttl);
		final emitter = entity.get(Emitter);

		for (col in collisionResult.collisions) {
			final health = col.entity.get(Health);

			if (health != null) {
				health.hit(fireBall.power * dt);

				if (health.current <= 0 && !col.entity.has(Kill))
					col.entity.add(new Kill());
			}
		}

		final r = fireBall.minRadius + (1 - (ttl.ttl / ttl.totalTtl)) * (fireBall.maxRadius - fireBall.minRadius);

		collisionCircle.radius = emitter.radius = r;
	}

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

			final col = [4, 5][Math.floor(Math.random() * 2)];

			frameBuffer.circle(spatial.x.int(), spatial.y.int(), collisionCircle.radius.int(), col, col);
		}
	}
}
