package ecs.systems;

import ecs.components.Health;
import ecs.components.HealthDisplay;
import ecs.components.Spatial;
import ecs.core.Entity;
import ecs.core.System;
import res.display.FrameBuffer;

using Std;

class DrawHealthDisplaySystem extends System {
	public function new() {
		super(Health, HealthDisplay, Spatial);
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final healthDisplay = entity.get(HealthDisplay);
		final health = entity.get(Health);

		if (!healthDisplay.show && healthDisplay.shownHealth != health.current) {
			healthDisplay.show = true;
			healthDisplay.shownHealth = health.current;
			healthDisplay.showTimer = healthDisplay.timeToShow;
		}

		if (healthDisplay.show) {
			if (healthDisplay.showTimer <= 0) {
				healthDisplay.showTimer = 0;
				healthDisplay.show = false;
			} else
				healthDisplay.showTimer -= dt;
		}
	}

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

			if (healthDisplay.show) {
				final health = entity.get(Health);
				final spatial = entity.get(Spatial);
				final healthPx = (healthDisplay.size * health.fraction).int();

				final fx = (spatial.x + healthDisplay.offsetX - healthDisplay.size / 2).int();

				for (line in 0...healthDisplay.height) {
					for (px in 0...healthDisplay.size) {
						frameBuffer.setIndex(fx + px, (spatial.y + healthDisplay.offsetY).int() + line, px <= healthPx ? 13 : 9);
					}
				}
			}
		}
	}
}
