package com.hh.lib_record;

import static com.hh.lib_base.Constants.LogcatValue.WARP;

import android.content.Context;
import android.util.Log;

import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.google.gson.JsonObject;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_ampe.utils.AromeInvoker;
import com.hh.lib_ampe.utils.MyTypeToken;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.ConfigData;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.ampe.BaseAmpeAppletResultBean;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.GsonUtils;
import com.hh.lib_base.utils.StringUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_record.bean.AmpeRequestRecordBean;
import com.hh.lib_record.bean.MicrophoneTypeEnum;
import com.hh.lib_record.microphone.IMicroPhoneSizeCallback;
import com.hh.lib_record.microphone.ZlwRecordManager;
import com.hh.lib_record.recorder.RecordService;

import org.json.JSONObject;

/**
 *
 * @author xwh
 * time 2024/9/10
 * Description: 实时语音调用器
 **/
public class RecordInvoker {

    private volatile static RecordInvoker invoker;
    private ZlwRecordManager zlwRecordManager;

    /**
     *
     * @author xwh
     * Time 2024/9/10
     * Description: 实时语音功能交互入口
     *
    **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        if(isUnEnabledHardware(dataBean,bridgeCallback)){
            AromeInvoker.getAromeInvoker()
                    .hardwareNotEnabled(dataBean, bridgeCallback);
            return;
        }
        switch (dataBean.getAction()) {
            case Constants.Ampe.ACTION_START_MICROPHONE_LISTENER:
                BaseAmpeRequestBean<AmpeRequestRecordBean> newBean= MyTypeToken.
                        toBaseAmpeRequestBean(dataBean,AmpeRequestRecordBean.class);
                boolean isMicrophoneSourceData = false;
                if (newBean.getParams() != null) {
                    isMicrophoneSourceData = newBean.getParams().isMicrophoneSourceData();
                }
                startMircophoneListener(isMicrophoneSourceData);
                recordCallBack(dataBean);
                break;
            case Constants.Ampe.ACTION_STOP_MICROPHONE_LISTENER:
                stopMicrophoneListener();
                recordCallBack(dataBean);
                break;
        }

    }

    /**
     *
     * @author xwh
     * Time 2024/12/13
     * Description: 是否未开启该模块
     * @return true:是该模块的消息并且未启用该模块
     **/
    private boolean isUnEnabledHardware(BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        DeviceConfigResultBean configResultBean = ConfigData.getDeviceConfigResultBean();
        boolean isOpenMicrophone = true;
        if (configResultBean != null) {
            isOpenMicrophone = configResultBean.isOpenMicrophone();
        }
        int microphoneType = configResultBean.getMicrophoneType();

        String action = dataBean.getAction();
        if(action != null && (Constants.Ampe.ACTION_START_MICROPHONE_LISTENER.equals(action) ||
                Constants.Ampe.ACTION_STOP_MICROPHONE_LISTENER.equals(action) )){
            if(!isOpenMicrophone){
                return true;
            }
            if(microphoneType != MicrophoneTypeEnum
                    .NATIVE_AUDI0.getValue()){  //MicrophoneTypeEnum.NATIVE_AUDI0.getValue() A原生语音) //不是A原生语音也拦截
                return true;
            }
        }
        return false;
    }

    // 麦克风
    public void initRecord(){
        String deviceModel = DeviceUtils.getDeviceModel();
        if (!Constants.DeviceModel.T1YB01.equals(deviceModel)) {
            // 非Y9
            return;
        }
        RecordService.stopRecording(BaseApplication.getContext());
        zlwRecordManager = ZlwRecordManager.getInstance(BaseApplication.getContext());
    }


    private void stopMicrophoneListener() {
        // 结束录音，主动推送
        if(zlwRecordManager==null){
            zlwRecordManager=ZlwRecordManager.getInstance(BaseApplication.getContext());
        }
        zlwRecordManager.stopRecordSize();
    }

    private void startMircophoneListener(boolean isMicrophoneSourceData) {
        if(zlwRecordManager==null){
            zlwRecordManager=ZlwRecordManager.getInstance(BaseApplication.getContext());
        }
        zlwRecordManager.startPCMRecordSize(isMicrophoneSourceData,new IMicroPhoneSizeCallback() {
            @Override
            public void onSizeSuccess(String result) {
        /*        StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("______________________123   ");
                stringBuilder.append(DateUtil.getTime("yyyy.MM.dd HH:mm:ss")
                        + " " + DateUtil.getWeekOfDate(new Date()));
                if (result != null) {
                    stringBuilder.append("   数据长度" + result.length() + "     ");
                    int end=result.length()/10;
                    if(end>0){
                        stringBuilder.append(result.substring(0,end));
                    }

                }
                if(tv_config_status!=null){
                    tv_config_status.setText(stringBuilder.toString());
                }
                AppLogUtils.e(stringBuilder);*/

                if (StringUtils.isNull(result)) {
                    return;
                }
                JSONObject object = new JSONObject();
                try {
                    // 勿动key，对外的文档key
                    object.put("voiceContent", result);
                } catch (Throwable t) {

                }
                if (AromeInvoker.getAromeInvoker() != null) {
                    // 主动推送给小程序
                    AromeInvoker.getAromeInvoker().sendMessageToApplet(Constants.Ampe.
                            EVENT_MICROPHONE_LISTENER, object.toString());
                }
            }

            @Override
            public void onMicrophoneSourceData(String data) {
                if (data==null) {
                    return;
                }

                JSONObject object = new JSONObject();
                try {
                    // 勿动key，对外的文档key
                    object.put("voiceContent", data);
                } catch (Throwable t) {

                }
                if (AromeInvoker.getAromeInvoker() != null) {
                    // 主动推送给小程序
                    AromeInvoker.getAromeInvoker().sendMessageToApplet(Constants.Ampe.
                            EVENT_MICROPHONE_LISTENER, object.toString());
                }
            }
        });
    }

    /**
     *
     * @author xwh
     * Time 2024/9/10
     * Description: 实时语音调用能力回调
     *
    **/
    private void recordCallBack(BaseAmpeRequestBean requestBean) {
        if (requestBean == null) {
            return;
        }
        BaseAmpeAppletResultBean bean = new BaseAmpeAppletResultBean();
        bean.setAction(requestBean.getAction());
        bean.setEvent(requestBean.getEvent());
        bean.setTaskId(requestBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("成功");
        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(bean).getAsJsonObject();
            if (requestBean.getBridgeCallback() != null) {
                requestBean.getBridgeCallback().callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append("jsonObject = ").append(jsonObject);
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_MICROPHONE,
                    "----" + requestBean.getAction(), logLine, logContentSb.toString());

        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }

    }

    public static RecordInvoker getInstance() {
        if (invoker == null) {
            synchronized (RecordInvoker.class) {
                if (invoker == null) {
                    invoker = new RecordInvoker();
                }
            }
        }
        return invoker;
    }


    public void onRelease() {
        if (zlwRecordManager != null) {
            zlwRecordManager.onRelease();
            zlwRecordManager = null;
        }
        invoker = null;
    }
}
