package com.gh.common.video

import android.content.Context
import android.net.Uri
import com.shuyu.gsyvideoplayer.cache.ICacheManager
import com.shuyu.gsyvideoplayer.cache.ICacheManager.ICacheAvailableListener
import tv.danmaku.ijk.media.exo2.ExoSourceManager
import tv.danmaku.ijk.media.player.IMediaPlayer
import java.io.File

/**
 * 基于ExoPlayerCacheManager修改，规避使用CustomExo2PlayerManager时的异常抛出
 */
class CustomExoPlayerCacheManager : ICacheManager {

    protected var mExoSourceManager: ExoSourceManager? = null
    override fun doCacheLogic(
        context: Context,
        mediaPlayer: IMediaPlayer,
        url: String,
        header: Map<String, String>,
        cachePath: File?
    ) {
        if (mediaPlayer !is CustomIjkExo2MediaPlayer) {
            throw UnsupportedOperationException("CustomExoPlayCacheManager only support CustomIjkExo2MediaPlayer")
        }
        mExoSourceManager = mediaPlayer.exoHelper
        //通过自己的内部缓存机制
        mediaPlayer.isCache = true
        mediaPlayer.cacheDir = cachePath
        mediaPlayer.setDataSource(context, Uri.parse(url), header)
    }

    override fun clearCache(context: Context, cachePath: File?, url: String) {
        ExoSourceManager.clearCache(context, cachePath, url)
    }

    override fun release() {
        mExoSourceManager = null
    }

    override fun hadCached(): Boolean {
        return mExoSourceManager != null && mExoSourceManager?.hadCached() == true
    }

    override fun cachePreview(context: Context, cacheDir: File?, url: String): Boolean {
        return ExoSourceManager.cachePreView(context, cacheDir, url)
    }

    override fun setCacheAvailableListener(cacheAvailableListener: ICacheAvailableListener) {}
}