package app.furmeet.events.system.schedule.managers

import android.content.Context
import android.content.res.Resources
import app.furmeet.events.system.helper.joinFile
import app.furmeet.events.system.helper.lastPathPart
import app.furmeet.events.system.helper.nullAndLogIfException
import app.furmeet.events.system.helper.nullFun
import java.io.File
import java.io.InputStream

class OfflineCacheManager(context: Context) : CacheManager() {

    private val assets = context.assets
    private val cacheDir = context.cacheDir
    override val goesOnline = false
    override val preloaded = false
    override fun getStamp(file: String): String? = get(file)?.second
    override fun get(file: String): Pair<InputStream, String>? = nullAndLogIfException {
        Pair(assets.open("out/$file"), UNIX_TIMESTAMP_START)
    }

    override fun fallbackGet(file: String): Pair<InputStream, String>? = get(file)

    override fun set(file: String, requestResult: Pair<ByteArray, String>) = nullFun()
    override fun delete(file: String) = false
    override fun sanitize() = 0
    override fun removeGarbageFiles() = 0
    override val files get() = assets.list("out")?.map { it.lastPathPart() }?.toSet() ?: setOf()
    override fun getFileFor(asset: String): File {
        val cachedFile = cacheDir.joinFile(asset.lastPathPart())
        if (!cachedFile.exists()) {
            val assetDescriptor = get(asset.lastPathPart())
            if (assetDescriptor == null)
                throw Resources.NotFoundException("Unavailable asset: $asset")
            else
                cachedFile.writeBytes(assetDescriptor.first.readBytes())
        }
        return cachedFile
    }
}