package melody.offline.music.util

import android.content.Context
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import androidx.media3.database.DatabaseProvider
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.cache.CacheEvictor
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
import androidx.media3.datasource.cache.NoOpCacheEvictor
import androidx.media3.datasource.cache.SimpleCache
import java.io.File

@OptIn(UnstableApi::class)
object CacheManager {
    private var playerCache: SimpleCache? = null
    private var downloadCache: SimpleCache? = null
    private var databaseProvider: DatabaseProvider? = null
    private const val DOWNLOAD_CONTENT_DIRECTORY = "DownloadOO"
    private const val PLAYER_CONTENT_DIRECTORY = "PlayerOO"

    fun initializeCaches(context: Context) {
        databaseProvider = StandaloneDatabaseProvider(context)

        // Initialize player cache
        val playerCacheDir = File(context.filesDir, PLAYER_CONTENT_DIRECTORY)
        val cacheEvictor: CacheEvictor = when (val size = ExoPlayerDiskCacheMaxSize.`1GB`) {
            ExoPlayerDiskCacheMaxSize.Unlimited -> NoOpCacheEvictor()
            else -> LeastRecentlyUsedCacheEvictor(size.bytes)
        }

        playerCache = SimpleCache(
            playerCacheDir,
            cacheEvictor,
            databaseProvider!!
        )

        // Initialize download cache
        val downloadCacheDir = File(context.filesDir, DOWNLOAD_CONTENT_DIRECTORY)
        downloadCache = SimpleCache(downloadCacheDir, NoOpCacheEvictor(), databaseProvider!!)
    }

    fun getPlayerCache(): SimpleCache? {
        return playerCache
    }

    fun getDownloadCache(): SimpleCache? {
        return downloadCache
    }
}
