package ru.dbotthepony.kstarbound.util

import kotlinx.coroutines.delay

/**
 * Allows to perform up to certain amount of actions per given time window,
 * otherwise starts throttling
 */
class ActionPacer(actions: Int, handicap: Int = 0) {
	private val delayBetween = 1_000_000_000L / actions
	private val maxBackwardNanos = handicap * delayBetween
	private var currentTime = System.nanoTime() - maxBackwardNanos

	suspend fun consume(actions: Int = 1) {
		require(actions >= 1) { "Invalid amount of actions to consume: $actions" }
		val time = System.nanoTime()

		if (time - currentTime > maxBackwardNanos)
			currentTime = time - maxBackwardNanos

		currentTime += delayBetween * (actions - 1)
		val diff = (currentTime - time) / 1_000_000L
		currentTime += delayBetween
		if (diff > 0L) delay(diff)
	}
}
