package ecs.systems;

import Math.*;
import ecs.components.OrbitPreview;
import ecs.components.Spatial;
import ecs.components.TriggerRadius;
import ecs.core.Entity;
import ecs.core.System;
import res.display.FrameBuffer;

using Std;
using res.graphics.Painter;

class DrawOrbitPreviewSystem extends System {
	var mouseX:Float;
	var mouseY:Float;

	public function new() {
		super(OrbitPreview);
	}

	public function setMousePos(x:Float, y:Float) {
		mouseX = x;
		mouseY = y;
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final orbitSystem = engine.getSystem(OrbitSystem);
		final orbit = orbitSystem.posToOrbit(mouseX, mouseY);

		final orbitHeight = OrbitSystem.snapOrbit(orbit.height);

		final orbitPreview = entity.get(OrbitPreview);
		orbitPreview.speed = OrbitSystem.heightToSpeed(orbitHeight);
		orbitPreview.previewPhase += orbitPreview.speed * orbitPreview.direction * dt;

		orbitPreview.rX = orbitPreview.rY = orbitHeight;

		var newDirection = orbitPreview.direction;

		final phaseDiff = orbit.phase - orbitPreview.lastFlipPhase;

		if (abs(phaseDiff) >= Math.PI / 16) { // TODO: Чем выше, тем меньше шаг
			orbitPreview.lastFlipPhase = orbit.phase;
			newDirection = phaseDiff < 0 ? 1 : -1;
		}

		orbitPreview.phase = orbit.phase;
		orbitPreview.direction = newDirection;

		entity.get(Spatial).set(mouseX, mouseY);
	}

	override function render(frameBuffer:FrameBuffer) {
		final orbitSystem = engine.getSystem(OrbitSystem);

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

			final numDots = floor(preview.rX / 10) * 5;

			for (n in 0...numDots) {
				final dp = (n / numDots) * (Math.PI * 2) + preview.previewPhase;
				final x = orbitSystem.centerX + sin(dp) * preview.rX;
				final y = orbitSystem.centerY + cos(dp) * preview.rY;

				frameBuffer.setIndex(x.int(), y.int(), 5);
			}

			if (triggerRadius != null) {
				frameBuffer.circle(spatial.x.int(), spatial.y.int(), triggerRadius.radius.int(), 4);
			}
		}
	}
}
