package ecs.systems;

import res.geom.Vector2;
import ecs.components.Orbiter;
import ecs.components.Spatial;
import ecs.core.Entity;
import ecs.core.System;

class OrbitSystem extends System {
	public static final MIN_ORBIT:Int = 20;
	public static final MAX_ORBIT:Int = 120;
	public static final ORBIT_STEP:Int = 10;
	public static final MAX_SPEED:Float = (Math.PI * 2) * 0.1;
	public static final MIN_SPEED:Float = (Math.PI * 2) * 0.01;

	public var centerX:Float;
	public var centerY:Float;

	public function new(centerX, centerY) {
		super(Orbiter, Spatial);

		this.centerX = centerX;
		this.centerY = centerY;
	}

	public static function heightToSpeed(h:Float):Float {
		return MIN_SPEED + (MAX_SPEED - MIN_SPEED) * (1 - ((h - MIN_ORBIT) / (MAX_ORBIT - MIN_ORBIT)));
	}

	public static function snapOrbit(h:Float) {
		return Math.min(MAX_ORBIT, Math.max(MIN_ORBIT, Math.floor(h / ORBIT_STEP) * ORBIT_STEP));
	}

	public function posToOrbit(atX:Float, atY:Float):{phase:Float, height:Float} {
		final orbital = engine.getSystem(OrbitSystem);

		final v = Vector2.xy(atX - orbital.centerX, atY - orbital.centerY);

		final phase = Math.atan2(v.y, v.x);
		final height = v.length();

		return {
			phase: phase,
			height: height
		};
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final orbiter = entity.get(Orbiter);
		final spatial = entity.get(Spatial);

		spatial.x = centerX + Math.cos(orbiter.phase) * orbiter.rX;
		spatial.y = centerY + Math.sin(orbiter.phase) * orbiter.rY;

		orbiter.phase += orbiter.angularSpeed * dt;
	}
}
