package com.ccwangluo.ccim.util;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;

import com.ccwangluo.ccim.listener.OnPlayAudioCallback;
import com.ccwangluo.ccim.listener.ResultEventCallback;
import com.ccwangluo.ccim.modle.MessageContent;

import java.io.File;

public class MediaHelper {
    private MediaRecorder mMediaRecorder;
    private String mFilePath;//文件

    private static MediaHelper mInstance;

    private MediaPlayer mediaPlayer;

    private Long start_record_millis = 0L;

    /**
     * 单例模式获取 MediaHelper
     */
    public static MediaHelper getInstance() {
        if (mInstance == null) {
            synchronized (MediaHelper.class) {
                if (mInstance == null) {
                    mInstance = new MediaHelper();
                }
            }
        }
        return mInstance;
    }

    /**
     * 准备录音
     */
    public void prepare(String path, int maxAudioDuration, ResultEventCallback<Void> resultCallback) {
        try {
            if (mMediaRecorder != null) {
                cancel();
            }
            String fileName = System.currentTimeMillis() + ".aac"; // 文件名字
            File file = new File(path, fileName);  // 文件路径
            mMediaRecorder = new MediaRecorder();
            mFilePath = file.getAbsolutePath();
            //设置保存文件的路径
            if (Build.VERSION.SDK_INT < 26) {
                //若api低于26，调用setOutputFile(String path)
                mMediaRecorder.setOutputFile(file.getAbsolutePath());
            } else {
                //若API高于26 使用setOutputFile(File path)
                mMediaRecorder.setOutputFile(new File(file.getAbsolutePath()));
            }
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);    // 设置MediaRecorder的音频源为麦克风
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//设置输出格式
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);// 编码方式 // 设置音频的编码为AMR_NB
            mMediaRecorder.setAudioSamplingRate(16000);
            mMediaRecorder.setAudioChannels(1);
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            start_record_millis = System.currentTimeMillis();

            resultCallback.onSuccess(null);
        } catch (Exception e) {
            resultCallback.onFailed(ErrorCode.START_VOICE_FAILED);
        }
    }

    /**
     * 释放资源,获取录音时长
     */
    public Long release() {
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
        if (start_record_millis != 0L) {
            long l = System.currentTimeMillis() - start_record_millis;
            start_record_millis = 0L;
            return l;
        }
        return 0L;
    }

    /**
     * 取消
     */
    public void cancel() {
        release();
        //删除相应的录音
        if (mFilePath != null) {
            File file = new File(mFilePath);
            if (file.exists()) {
                file.delete();
            }
            mFilePath = null;
        }
    }

    /**
     * 播放
     *
     * @param filePath
     */
    public void play(String filePath, OnPlayAudioCallback resultCallback, Float volume) {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        } else {
//            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = new MediaPlayer();
        }
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setVolume(volume, volume);
            mediaPlayer.prepare();
            mediaPlayer.start();
            resultCallback.onStart();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    resultCallback.onSuccess();
                }
            });
        } catch (Exception e) {
            resultCallback.onFailed(ErrorCode.ERROR_VOICE_PLAY);
        }
    }

    //获取生成的文件路径
    public String getFilePath(String filename, String path) {
        return FileUtils.renameFile(mFilePath, path, filename);
    }

    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}