package ecs.systems;

import ecs.components.Aim;
import ecs.components.Health;
import ecs.components.Kill;
import ecs.components.LaserGun;
import ecs.components.Spatial;
import ecs.core.Entity;
import ecs.core.System;
import res.display.FrameBuffer;
import res.geom.Vector2;

using Std;
using res.graphics.Painter;

class LaserGunSystem extends System {
	public function new() {
		super(Spatial, Aim, LaserGun);
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final aim = entity.get(Aim);
		final laserGun = entity.get(LaserGun);

		if (aim.targets.length > 0) {
			if (laserGun.target == null)
				laserGun.target = aim.targets[Math.floor(aim.targets.length * Math.random())];

			final targetHealth = laserGun.target.get(Health);

			if (targetHealth != null && targetHealth.current > 0) {
				if (laserGun.chargeTime >= laserGun.totalChargeTime) {
					laserGun.chargeTime = laserGun.totalChargeTime;

					if (targetHealth != null) {
						targetHealth.hit(laserGun.strength * dt);

						if (targetHealth.current <= 0) {
							laserGun.target.add(new Kill());
						}
					}
				} else
					laserGun.chargeTime += dt;
			} else {
				laserGun.chargeTime = 0;
				laserGun.target = null;
			}
		} else {
			laserGun.chargeTime = 0;
			laserGun.target = null;
		}
	}

	override function render(frameBuffer:FrameBuffer) {
		for (entity in entities) {
			final laserGun = entity.get(LaserGun);

			if (laserGun.target != null) {
				final spatial = entity.get(Spatial);
				final targetSpatial = laserGun.target.get(Spatial);

				final v = Vector2.xy(targetSpatial.x - spatial.x, targetSpatial.y - spatial.y);

				final laserOrigin = Vector2.xy(spatial.x, spatial.y).add(v.normalize(5));

				final charge = laserGun.chargeTime / laserGun.totalChargeTime;

				frameBuffer.circle(laserOrigin.x.int(), laserOrigin.y.int(), (1.5 * charge).int(), 5, 5);

				if (laserGun.chargeTime >= laserGun.totalChargeTime) {
					frameBuffer.line(laserOrigin.x.int(), laserOrigin.y.int(), targetSpatial.x.int(), targetSpatial.y.int(), 5);
				}
			}
		}
	}
}
