import res.Sprite;
import res.Object;

using Math;

class Coin extends Object {
	var onPickUP:Void->Void;

	final totalDropTime:Float;
	var dropTime:Float = 0;

	final totalCollectTime:Float;
	var collectTime:Float = 0;

	var fromX:Float;
	var fromY:Float;
	var dropX:Float;
	var dropY:Float;

	public function new(sprite:Sprite, fromX:Float, fromY:Float, pickUP:Void->Void) {
		super(sprite);
		this.onPickUP = pickUP;

		totalDropTime = 0.1 + Math.random() * 0.3;

		totalCollectTime = 0.5 + 0.5 * Math.random();

		x = this.fromX = fromX;
		y = this.fromY = fromY;

		final r = -Math.PI / 2 + Math.PI * Math.random();
		final l = 5 + 15 * Math.random();

		dropX = x + Math.sin(r) * l - sprite.width / 2;
		dropY = y + Math.cos(r) * l - sprite.height / 2;

		wrap = false;
	}

	override function update(dt:Float) {
		super.update(dt);

		if (dropTime <= totalDropTime) {
			final t = dropTime / totalDropTime;

			x = fromX + (dropX - fromX) * (1 - (1 - t).pow(3));
			y = fromY + (dropY - fromY) * (1 - (1 - t).pow(3));

			dropTime += dt;
		} else {
			if (collectTime <= totalCollectTime) {
				final t = collectTime / totalCollectTime;

				x = dropX + (80 - dropX) * (t * t * t * t);
				y = dropY + (4 - dropY) * (t * t * t * t);

				collectTime += dt;
			} else {
				toRemove = true;
				onPickUP();
			}
		}
	}
}
