package com.github.libretube.util

import android.content.Context
import androidx.media3.common.util.UnstableApi
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.cache.CacheDataSource
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
import androidx.media3.datasource.cache.SimpleCache
import java.io.File

/**
 * On-the-fly media cache used by ExoPlayer.
 * Downloads remain independent and permanent; this cache is LRU and may be evicted by size.
 */
@UnstableApi
object PlaybackCache {
    private const val MAX_CACHE_BYTES = 256L * 1024L * 1024L

    @Volatile
    private var simpleCache: SimpleCache? = null

    private fun getCache(context: Context): SimpleCache {
        simpleCache?.let { return it }
        return synchronized(this) {
            simpleCache ?: SimpleCache(
                File(context.applicationContext.cacheDir, "playback_media_cache"),
                LeastRecentlyUsedCacheEvictor(MAX_CACHE_BYTES),
                StandaloneDatabaseProvider(context.applicationContext)
            ).also { simpleCache = it }
        }
    }

    fun dataSourceFactory(context: Context): DataSource.Factory {
        val upstream = DefaultDataSource.Factory(context.applicationContext)
        return CacheDataSource.Factory()
            .setCache(getCache(context))
            .setUpstreamDataSourceFactory(upstream)
            .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
    }
}
