package com.audio.record.screen.test.tool

import android.media.MediaMetadataRetriever
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.arthenica.ffmpegkit.FFmpegKit
import com.arthenica.ffmpegkit.ReturnCode
import com.audio.record.screen.test.App
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.util.concurrent.TimeUnit

object FFmpegKitTool {

    val mainHandler = Handler(Looper.getMainLooper())

    fun copy(
        tempFile: File,
        inputStream: InputStream,
        thumbDir: String,
        result: (ok: Boolean) -> Unit
    ) {

        FileOutputStream(tempFile).use { outputStream ->
            inputStream.copyTo(outputStream)
            outputStream.flush()
            extractThumbnailsFFmpeg(tempFile.absolutePath, thumbDir, result)
        }

    }

    fun createThumb(inputPath: String, outputDir: String, result: (ok: Boolean) -> Unit) {
//        val inputPath = "/storage/emulated/0/Movies/sample.mp4"
//        val outputDir = "/storage/emulated/0/Movies/thumbs" // 请确保已创建
        val cmd = "-i $inputPath -vf fps=10 $outputDir/thumb_%04d.jpg"

        FFmpegKit.executeAsync(cmd) { session ->
            val returnCode = session.returnCode
            if (ReturnCode.isSuccess(returnCode)) {
                Common.showLog("FFmpegKit 缩略图生成成功   ${Thread.currentThread().name}")
                result.invoke(true)
            } else {
                result.invoke(false)
                Common.showLog("FFmpegKit  缩略图生成失败：${session.failStackTrace}")
            }
        }

    }


    /**
     * 截取视频缩略图，均分6张图
     */
    fun extractThumbnailsFFmpeg(
        videoPath: String,
        outputDir: String,
        result: (ok: Boolean) -> Unit
    ) {
        var count = 0
        val durationMs = Common.getVideoDurationMs(videoPath)
        val durationSec = durationMs / 1000.0
        val step = durationSec / 7  // 均分6帧，跳过首尾
        Common.showLog("durationSec $durationSec step $step")
        for (i in 1..6) {
            val timestamp = i * step
            val outputPath = "$outputDir/thumb_$i.jpg"
            Common.showLog("i = $i timestamp $timestamp ")
            val cmd = "-ss $timestamp -i \"$videoPath\" -frames:v 1 -q:v 2 \"$outputPath\""
            FFmpegKit.executeAsync(cmd) { session ->
                val returnCode = session.returnCode
                count++
                if (count == 6) {
                    mainHandler.post {
                        if (returnCode.isValueSuccess) {
                            result.invoke(true)
                            Common.showLog("FFmpeg Frame $i saved to $outputPath")
                        } else {
                            result.invoke(false)
                            Common.showLog("FFmpeg  Failed to extract frame $i")
                        }

                    }
                }


            }
        }
    }


    /**
     * 剪切视频时长
     * @param startTime
     */
    fun cropVideoWithFFmpeg(
        inputPath: String,
        outputPath: String,
        startMs: Float,
        endMs: Float
    ) {
        val durationMs = endMs - startMs
        if (durationMs <= 0) {
            println("结束时间必须大于开始时间")
            return
        }
        val formatFloatTime = formatFloatTime(durationMs)
        val startTime = formatFloatTime(startMs)
        val endTime = formatFloatTime(endMs)
        val command =
            "-ss $startTime -i \"$inputPath\" -to $formatFloatTime -c:v copy -c:a copy \"$outputPath\""
        Common.showLog("--command=${command}")

        FFmpegKit.executeAsync(command) { session ->
            val returnCode = session.returnCode
            if (returnCode.isValueSuccess) {
                Common.showLog("裁剪成功: $outputPath")
            } else {
                Common.showLog("裁剪失败: ${session.failStackTrace}")
            }
        }
    }

    // 毫秒转为 ffmpeg 时间格式：hh:mm:ss.S
    fun formatFloatTime(ms: Float): String {
        val totalSeconds = ms / 1000f
        val hours = (totalSeconds / 3600).toInt()
        val minutes = ((totalSeconds % 3600) / 60).toInt()
        val seconds = (totalSeconds % 60).toInt()
        val tenths = ((totalSeconds % 1) * 10).toInt() // 保留一位小数

        return String.format("%02d:%02d:%02d.%01d", hours, minutes, seconds, tenths)
    }
//
//    fun trimVideo(inputPath: String, outputPath: String, startTime: String, endTime: String) {
//        val command = "-ss $startTime -i $inputPath -to $endTime -c copy $outputPath"
//
//          Common.showLog("--command=${command}")
//
//        FFmpegKit.executeAsync(command) { session ->
//            when {
//                ReturnCode.isSuccess(session.returnCode) -> {
//                    Log.d("FFmpegKit", "剪切成功！输出路径: $outputPath")
//                }
//
//                session.returnCode.value == ReturnCode.CANCEL -> {
//                    Log.w("FFmpegKit", "用户取消操作")
//                }
//
//                else -> {
//                    Log.e("FFmpegKit", "剪切失败. 错误日志: ${session.output}")
//                }
//            }
//        }
//    }


    /**
     * 裁切视频显示内容尺寸
     */
    fun cropVideo(
        inputPath: String,
        outputPath: String,
        cropX: Int,
        cropY: Int,
        cropWidth: Int,
        cropHeight: Int
    ) {
//        val cmd = "-i $inputPath -vf crop=$cropWidth:$cropHeight:$cropX:$cropY -c:a copy $outputPath"
        val cmd =
            "-i $inputPath -vf crop=$cropWidth:$cropHeight:$cropX:$cropY -c:v mpeg4 -qscale:v 2 -c:a copy $outputPath"

        Common.showLog("FFmpeg Crop 比例裁剪   $cmd")
        FFmpegKit.executeAsync(cmd) {
            if (ReturnCode.isSuccess(it.returnCode)) {
                Common.showLog("FFmpeg Crop 比例裁剪成功  $outputPath")
            } else {
                Common.showLog("FFmpeg Crop 比例裁剪失败： $outputPath ${it.failStackTrace}")
            }
        }
    }


    /**
     * 调整视频音量
     */
    fun setVideVolume(
        inputPath: String,
        outputPath: String, volumeLevel: Float
    ) {
//        val volumeLevel = 1.5  // 音量倍数（例如 1.5 表示音量加大 50%）
        val cmd = "-y -i $inputPath -filter:a volume=$volumeLevel -c:v copy $outputPath"
        Common.showLog("FFmpeg 音量   $cmd")
        FFmpegKit.executeAsync(cmd) { session ->
            val returnCode = session.returnCode
            if (ReturnCode.isSuccess(returnCode)) {
                Common.showLog("FFmpeg 音量调节成功")
            } else {
                Common.showLog("FFmpeg  音量调节失败: ${session.failStackTrace}")
            }
        }

    }

    /**
     * 调整视频播放速度
     */
    fun buildSpeedCommand(inputPath: String, outputPath: String, speed: Float) {
        val videoFilter = "setpts=${1 / speed}*PTS"
        val audioFilter = "atempo=$speed"
        val cmd = "-y -i $inputPath -filter_complex \"[0:v]$videoFilter[v];[0:a]$audioFilter[a]\" -map \"[v]\" -map \"[a]\" -preset ultrafast $outputPath"
        Common.showLog("FFmpeg 播放速度调整   $cmd")
        FFmpegKit.executeAsync(cmd) { session ->
            if (ReturnCode.isSuccess(session.returnCode)) {
                Common.showLog("FFmpeg 播放速度调整成功")
            } else {
                Common.showLog("FFmpeg  播放速度调整失败: ${session.failStackTrace}")
            }
        }

    }

}