// manager/AudioPlayManager.kt
package com.example.initiateaphonecallapp.manager

import android.media.MediaPlayer
import android.util.Log
import java.io.IOException

object AudioPlayManager {
    private const val TAG = "AudioPlayManager"

    private var mediaPlayer: MediaPlayer? = null
    private var currentAudioUrl: String? = null
    private var isPlaying:Boolean = false

    /**
     * 播放音频
     * @param audioUrl 音频文件URL（可以是网络URL或本地文件路径）
     * @param onStart 播放开始回调
     * @param onCompletion 播放完成回调
     * @param onError 播放错误回调
     */
    fun playAudio(
        audioUrl: String,
        onStart: (() -> Unit)? = null,
        onCompletion: (() -> Unit)? = null,
        onError: ((String) -> Unit)? = null
    ) {
        // 如果正在播放同一个音频，则停止播放
        if (isPlaying && currentAudioUrl == audioUrl) {
            stopAudio()
            return
        }

        // 停止之前的播放
        stopAudio()

        try {
            mediaPlayer = MediaPlayer().apply {
                // 设置数据源
                setDataSource(audioUrl)

                // 准备异步播放
                setOnPreparedListener { mp ->
                    mp.start()
                    currentAudioUrl = audioUrl
                    onStart?.invoke()
                    Log.d(TAG, "开始播放音频: $audioUrl")
                }

                // 播放完成监听
                setOnCompletionListener { mp ->
                    currentAudioUrl = null
                    onCompletion?.invoke()
                    Log.d(TAG, "音频播放完成: $audioUrl")
                }

                // 错误监听
                setOnErrorListener { mp, what, extra ->
                    currentAudioUrl = null
                    val errorMsg = "播放错误: what=$what, extra=$extra"
                    onError?.invoke(errorMsg)
                    Log.e(TAG, errorMsg)
                    true
                }

                // 准备播放
                prepareAsync()
            }
        } catch (e: IOException) {
            val errorMsg = "音频文件无法访问: ${e.message}"
            onError?.invoke(errorMsg)
            Log.e(TAG, errorMsg)
        } catch (e: IllegalArgumentException) {
            val errorMsg = "音频文件格式错误: ${e.message}"
            onError?.invoke(errorMsg)
            Log.e(TAG, errorMsg)
        } catch (e: SecurityException) {
            val errorMsg = "没有音频播放权限: ${e.message}"
            onError?.invoke(errorMsg)
            Log.e(TAG, errorMsg)
        }
    }

    /**
     * 停止播放
     */
    fun stopAudio() {
        mediaPlayer?.let { mp ->
            if (mp.isPlaying) {
                mp.stop()
            }
            mp.release()
        }
        mediaPlayer = null
        isPlaying = false
        currentAudioUrl = null
        Log.d(TAG, "停止音频播放")
    }

    /**
     * 暂停播放
     */
    fun pauseAudio() {
        mediaPlayer?.let { mp ->
            if (mp.isPlaying) {
                mp.pause()
                isPlaying = false
                Log.d(TAG, "暂停音频播放")
            }
        }
    }

    /**
     * 恢复播放
     */
    fun resumeAudio() {
        mediaPlayer?.let { mp ->
            if (!mp.isPlaying && currentAudioUrl != null) {
                mp.start()
                isPlaying = true
                Log.d(TAG, "恢复音频播放")
            }
        }
    }

    /**
     * 获取当前播放状态
     */
    fun isPlaying(): Boolean = isPlaying

    /**
     * 获取当前播放的音频URL
     */
    fun getCurrentAudioUrl(): String? = currentAudioUrl

    /**
     * 检查是否正在播放指定音频
     */
    fun isPlaying(audioUrl: String): Boolean = isPlaying && currentAudioUrl == audioUrl
}