package xn.hxp.util;

import android.media.MediaPlayer;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;

/**
 * 播放音频
 */
public class AudioPlayerTool {
    private static AudioPlayerTool instance;
    private MediaPlayer mediaPlayer;
    private int currentAudioResId = 0;

    private AudioPlayerTool() {
        // 私有构造函数，防止外部创建实例
    }

    public static interface OnPlayListener {
        void ended();
    }

    public static synchronized AudioPlayerTool getInstance() {
        if (instance == null) {
            instance = new AudioPlayerTool();
        }
        return instance;
    }

    public synchronized void play(int audioResId) {
        if (mediaPlayer != null && currentAudioResId == audioResId) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
            return;
        }
        stop();
        try {
            mediaPlayer = MediaPlayer.create(Utils.getApp(), audioResId);
            if (mediaPlayer != null) {
                mediaPlayer.start();
                currentAudioResId = audioResId;
                mediaPlayer.setOnCompletionListener(mp -> stop());
            } else {
                LogUtils.e("Failed to create MediaPlayer for resource ID: " + audioResId);
            }
        } catch (Exception e) {
            LogUtils.e("Error playing audio resource: " + audioResId, Log.getStackTraceString(e));
        }
    }

    public synchronized void play(int audioResId, OnPlayListener onPlayListener) {
        if (mediaPlayer != null && currentAudioResId == audioResId) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
            return;
        }
        stop();
        try {
            mediaPlayer = MediaPlayer.create(Utils.getApp(), audioResId);
            if (mediaPlayer != null) {
                mediaPlayer.start();
                currentAudioResId = audioResId;
                mediaPlayer.setOnCompletionListener(mp -> {
                    stop();
                    onPlayListener.ended();
                });
            } else {
                LogUtils.e("Failed to create MediaPlayer for resource ID: " + audioResId);
            }
        } catch (Exception e) {
            LogUtils.e("Error playing audio resource: " + audioResId, Log.getStackTraceString(e));
        }
    }

    public void stop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
            currentAudioResId = 0;
        }
    }

    public boolean isPlaying() {
        return mediaPlayer != null && mediaPlayer.isPlaying();
    }
}
