package cn.muchinfo.rma.lifecycle

import android.os.SystemClock
import java.util.concurrent.TimeUnit

interface Antiquated<in KEY> {
    fun shouldFetch(key: KEY): Boolean
}

class RateLimiter<in KEY>(
        private var timeout: Long,
        timeUnit: TimeUnit
) : Antiquated<KEY> {

    init {
        timeout = timeUnit.toMillis(timeout)
    }

    private val timestamps: HashMap<KEY, Long> = hashMapOf()

    @Synchronized
    override fun shouldFetch(key: KEY): Boolean {
        val lastFetched = timestamps[key]
        val now = SystemClock.uptimeMillis()
        if (lastFetched == null) {
            timestamps.put(key, now)
            return true
        }
        if (now - lastFetched > timeout) {
            timestamps.put(key, now)
            return true
        }
        return false
    }

    @Synchronized
    fun leftTime(key: KEY): Long {
        val lastFetched = timestamps[key] ?: return 0
        val now = SystemClock.uptimeMillis()
        val overTime = now - lastFetched
        if (overTime > timeout) {
            return 0
        }
        return timeout - overTime
    }

    @Synchronized
    fun reset(key: KEY) {
        timestamps.remove(key)
    }
}