package com.hh.lib_record.microphone;

import android.content.Context;
import android.media.AudioFormat;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;

import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.LogType;
import com.hh.lib_record.RecordManager;
import com.hh.lib_record.recorder.RecordConfig;
import com.hh.lib_record.recorder.RecordHelper;
import com.hh.lib_record.recorder.RecordService;
import com.hh.lib_record.recorder.listener.RecordDataListener;
import com.hh.lib_record.utils.FileUtils;

import java.io.File;
import java.util.Arrays;
import java.util.Locale;

public class ZlwRecordManager {

    private final String TAG=ZlwRecordManager.class.getName();
    //用volatile关键字确保 instance 在多线程下的可见性
    private static volatile ZlwRecordManager instance = null;

    Context mContext;
    // 文件夹——包含所有录音文件
    String recordFile = "/storage/emulated/0/Record/arome/";
    // 录音文件
    File file;
    // 录音文件地址
    String filePath;

    volatile IMicroPhoneSizeCallback iMicroPhoneSizeCallback=null;
    volatile boolean isSourceData=false; //麦克风传输格式选择 true:byte[] false:base64

    private Handler mainHandler = new Handler(Looper.getMainLooper());
    public Handler getMainHandler() {
        if(mainHandler==null){
            synchronized (ZlwRecordManager.class){
                if(mainHandler==null){
                    mainHandler=new Handler(Looper.getMainLooper());
                }
            }
        }
        return mainHandler;
    }

    //提供一个公共的访问方法，用于获取该类的唯一实例
    public static ZlwRecordManager getInstance(Context context) {
        //如果instance为空，就进行实例化
        if (instance == null) {
            //保证多线程下只有一个线程进行实例化
            synchronized (ZlwRecordManager.class) {
                //第二次判断，避免多线程下创建多个实例
                if (instance == null) {
                    instance = new ZlwRecordManager(context);
                }
            }
        }
        return instance;
    }



    public ZlwRecordManager(Context context) {
        this.mContext = context;
        init();
    }

    private void init() {
        RecordManager recordManager= RecordManager.getInstance();
        recordManager.init(BaseApplication.getInstance(), true);
        //Todo 使用MP3/WAV格式需要测试一下，底层有改动 time:2024/07/26
        recordManager.changeFormat(RecordConfig.RecordFormat.PCM);
        recordManager.changeRecordConfig(recordManager.getRecordConfig().setSampleRate(16000));
        recordManager.changeRecordConfig(recordManager.getRecordConfig().setEncodingConfig(AudioFormat.ENCODING_PCM_16BIT));
        String recordDir = String.format(Locale.getDefault(), "%s/Record/arome/",
                Environment.getExternalStorageDirectory().getAbsolutePath());
        recordManager.changeRecordDir(recordDir);
        filePath = RecordService.getFilePath();
        AppLogUtils.e("录音文件filePath：" + filePath);
        file = FileUtils.getFileByPath(filePath);
        recordManager.setRecordDataListener(recordDataListener);
        recordManager.start();
    }


    RecordDataListener recordDataListener=new RecordDataListener() {
        @Override
        public void onData(byte[] data) { //已经移动到子线程运行
            if(iMicroPhoneSizeCallback!=null&&data!=null&&data.length>0){
                if(isSourceData){
                    String arr= Arrays.toString(data);

                    getMainHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            if(iMicroPhoneSizeCallback!=null) {
                                iMicroPhoneSizeCallback.onMicrophoneSourceData(arr);
                            }
                        }
                    });
                }else{
                    String resaultData=encodeToString(data);
                    getMainHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            if(iMicroPhoneSizeCallback!=null) {
                                iMicroPhoneSizeCallback.onSizeSuccess(resaultData);
                            }
                        }
                    });
                }


            }
        }
    };


    /**
     * 持续发送--开始
     * @param iMicroPhoneSizeCallback
     */
    public synchronized void startPCMRecordSize(boolean isMicrophoneSourceData, IMicroPhoneSizeCallback iMicroPhoneSizeCallback) {
        RecordManager recordManager= RecordManager.getInstance();
        if(recordManager.getState()!= RecordHelper.RecordState.RECORDING){
            try {
                recordManager.stop();
                getMainHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        recordManager.start();
                    }
                },200);
            }catch (Exception e){
                AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                        .append(e.toString())
                        .toString());
                AppLogUtils.e(TAG+"    "+e.toString());
            }

        }
        isSourceData=isMicrophoneSourceData;
        if(this.iMicroPhoneSizeCallback!=null){
            return;
        }
        this.iMicroPhoneSizeCallback = iMicroPhoneSizeCallback;
    }

    /**
     * 持续发送的--停止
     */
    public synchronized void stopRecordSize() {
        this.iMicroPhoneSizeCallback = null;
    }

    public synchronized void getState(IMicroPhoneStateCallback iMicroPhoneStateCallback){
        if(iMicroPhoneStateCallback!=null){
            if(iMicroPhoneSizeCallback==null){
                iMicroPhoneStateCallback.onState(0); //todo 对于客户来讲，没录音
            }else{
                iMicroPhoneStateCallback.onState(1);//todo 对于客户来讲，录音中
            }
        }

    }

    public void onRelease(){
        RecordManager recordManager=RecordManager.getInstance();
        if (recordManager != null) {
            recordManager.release();
        }
        if(mainHandler!=null){
            mainHandler.removeCallbacksAndMessages(null);
            mainHandler=null;
        }
        instance = null;

    }


    public static String encodeToString(byte[] data) {
        return android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
    }
}
