package com.adealink.weparty.commonui.mediapicker.imageselect.util

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import com.adealink.frame.base.CommonIOError
import com.adealink.frame.base.Rlt
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.storage.file.imageProgressPath
import com.adealink.frame.util.closeQuietly
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

suspend fun getVideoThumbnail(path: String): Rlt<String> {
    return withContext(Dispatcher.WENEXT_THREAD_POOL) {
        var bitmap: Bitmap? = null
        var exception: Exception? = null
        val retriever = MediaMetadataRetriever()
        try {
            retriever.setDataSource(path)
            bitmap = retriever.frameAtTime
        } catch (e: Exception) {
            exception = e
        } finally {
            try {
                retriever.release()
            } catch (ex: RuntimeException) {

            }
        }

        if (bitmap == null) {
            return@withContext Rlt.Failed(CommonIOError(exception ?: IOException()))
        }

        val saveFile =
            File(imageProgressPath, "${System.currentTimeMillis()}_video_thumbnail.jpg")
        var fos: FileOutputStream? = null
        try {
            fos = FileOutputStream(saveFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            return@withContext Rlt.Success(saveFile.absolutePath)
        } catch (e: Exception) {
            return@withContext Rlt.Failed(CommonIOError(e))
        } finally {
            closeQuietly(fos)
            bitmap.recycle()
        }
    }
}