package ecs.systems;

import ecs.core.System;
import res.display.FrameBuffer;

using Std;

class ShakeSystem extends System {
	final frameBuffer:FrameBuffer;

	var time:Float;
	var totalTime:Float;
	var amp:Float;
	var shaking:Bool = false;

	public function new(frameBuffer:FrameBuffer) {
		super();

		this.frameBuffer = frameBuffer;
	}

	public function shake(amp:Float, time:Float) {
		this.amp = amp;
		this.totalTime = time;
		this.time = 0;
		this.shaking = true;
	}

	override function update(dt:Float) {
		if (shaking) {
			if (time <= totalTime) {
				final t = Math.pow(1 - (time / totalTime), 3);

				frameBuffer.scrollX = (amp * t * Math.random()).int();
				frameBuffer.scrollY = (amp * t * Math.random()).int();

				if (time == totalTime)
					shaking = false;
				else {
					time += dt;

					if (time > totalTime)
						time = totalTime;
				}
			}
		}
	}
}
