package de.sebse.fuplanner2.database

import androidx.room.Entity

@Entity(primaryKeys = ["uid", "type"])
data class Cache (
    val uid: String,
    val type: String,
    val lastRefreshed: Long,
    val cache: String
) {
    companion object {
        suspend fun getCache(database: AppDatabase, uid: String, type: String, refreshInterval: Long, onCreateNew: (suspend () -> String)): String {
            val cacheDao = database.cacheDao()
            val cache = cacheDao.getCache(uid, type)?.let {
                if (System.currentTimeMillis() <= it.lastRefreshed + refreshInterval) {
                    it
                } else {
                    cacheDao.delete(it)
                    null
                }
            } ?: run {
                val c = Cache(uid, type, System.currentTimeMillis(), onCreateNew())
                cacheDao.insert(c)
                c
            }
            return cache.cache
        }
    }
}
