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

import android.media.MediaMetadataRetriever
import com.adealink.frame.base.CommonIOError
import com.adealink.frame.base.Rlt
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import kotlinx.coroutines.withContext

suspend fun getVideoDuration(path: String): Rlt<Long> {
    return withContext(Dispatcher.WENEXT_THREAD_POOL) {
        val retriever = MediaMetadataRetriever()
        try {
            // 设置数据源，支持文件路径、URI、FileDescriptor等
            retriever.setDataSource(path)

            // 提取时长元数据（返回毫秒值的字符串）
            val durationStr =
                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)

            // 转换为Long类型（毫秒）
            return@withContext Rlt.Success(durationStr?.toLong() ?: 0L)
        } catch (e: Exception) {
            return@withContext Rlt.Failed(CommonIOError(e))
        } finally {
            // 重要：释放资源
            retriever.release()
        }
    }
}