package com.hh.lib_asr;

import static com.hh.lib_base.Constants.Ampe.ACTION_DOASR;

import android.content.Context;
import android.text.TextUtils;

import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.google.gson.JsonObject;
import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
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_asr.bean.AmpeAsrRequestBean;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.ConfigData;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.GsonUtils;
import com.mpaas.asrlibrary.AsrSDK;
import com.mpaas.asrlibrary.onAudioRecordListener;

/**
 * Description: $
 *
 * @author xwh
 * time 2024/11/13
 **/
public class ASRInvoker {

    private volatile static ASRInvoker invoker;


    /**
     *
     * @author xwh
     * Time 2024/11/13
     * 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;
        }
        if (!ACTION_DOASR.equals(dataBean.getAction())) { //TODO 不是ASR语音识别功能，return
            return;
        }
        switch (dataBean.getEvent()){ //TODO 注意：此处是event，并不是action
            case Constants.Ampe.EVENT_INIT:
                initASR(dataBean);
                break;
            case Constants.Ampe.EVENT_START:
                startASR(dataBean);
                break;
            case Constants.Ampe.EVENT_STOP:
                stopASR(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_DOASR.equals(action)){
            if(!isOpenMicrophone ){
                return true;
            }
            if(microphoneType != 2 ){   //MicrophoneTypeEnum.ASR.getValue() ASR语音) //不是ASR语音也拦截
                return true;
            }
        }
        return false;
    }

    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: 初始化语音识别
     *
    **/
    public void initASR( BaseAmpeRequestBean requestBean){

        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeAsrRequestBean> newRequestBean = MyTypeToken
                .toBaseAmpeRequestBean(requestBean, AmpeAsrRequestBean.class);
        if (newRequestBean == null || newRequestBean.getParams() == null) {
            initASRCallBackJson("asrError","参数不对");
            return;
        }
        AmpeAsrRequestBean params=newRequestBean.getParams();
        String language = "cn"; //语言
        if(TextUtils.isEmpty(params.getTenantCode())) {
            initASRCallBackJson("asrError","租户ID为空");
            return;
        }
        if(!TextUtils.isEmpty(params.getLang())){
            language = params.getLang();
        }

        try {
            AsrSDK.getInstance().initNui(BaseApplication.getContext(), language, params.getTenantCode(), new onAudioRecordListener() {
                @Override
                public void onEventRecordStart() {
                    //⻨克⻛已开启
                    String logLine = (new Throwable().getStackTrace())[0].toString();
                    UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_ASR,
                            "",logLine
                            ,"⻨克⻛已开启---");
                    initASRCallBackJson("asrRecordStart","⻨克⻛已开启");
                }

                @Override
                public void onEventAsrPartialResult(String s) {
                    //语⾳识别中的⽂本数据
                    initASRCallBackJson("asrPartialResult",""+s);
                }

                @Override
                public void onEventSentenceEnd(String s) {
                    //语⾳识别结束的⽂本数据
                    initASRCallBackJson("sentenceEnd",""+s);
                }

                @Override
                public void onEventRecordEnd() {
                    //⻨克⻛已关闭
                    String logLine = (new Throwable().getStackTrace())[0].toString();
                    UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_ASR,
                            "",logLine
                            ,"⻨克⻛已关闭---");
                    initASRCallBackJson("asrRecordEnd","⻨克⻛已关闭");
                }

                @Override
                public void onEventMicError() {
                    //表示2s未传⼊⾳频数据，请检查录⾳相关代码、权限或录⾳模块是否被其他应⽤占⽤。
                    initASRCallBackJson("micError","");
                }

                @Override
                public void onEventAsrError(int i) {
                    // 语⾳识别错误
                    initASRCallBackJson("asrError",""+i);
                }
            });
        }catch (Exception e){
            initASRCallBackJson("asrError",e.toString());
        }
        callback(requestBean);
    }


    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: 启动语音识别
     *
     **/
    public void startASR(BaseAmpeRequestBean requestBean){
        AsrSDK.getInstance().startAsr();
        callback(requestBean);
    }

    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: 停止语音识别
     *
     **/
    public void stopASR(BaseAmpeRequestBean requestBean){
        AsrSDK.getInstance().stopAsr();
        callback(requestBean);
    }

    /**
     *
     * @author xwh
     * Time 2024/11/15
     * Description: 启动/停止语音识别回调
     *
    **/
    public void callback(BaseAmpeRequestBean requestBean){
        if (requestBean == null) {
            return;
        }
        BaseAmpeAppletResultBean resultBean = new BaseAmpeAppletResultBean();
        resultBean.setAction(requestBean.getAction());
        resultBean.setEvent(requestBean.getEvent());
        resultBean.setTaskId(requestBean.getTaskId());
        resultBean.setSuccess(true);
        resultBean.setMessage("成功");
        JsonObject jsonObject = GsonUtils.getGson().toJsonTree(resultBean).getAsJsonObject();
        if (requestBean.getBridgeCallback() != null) {
            requestBean.getBridgeCallback() .callback(jsonObject.toString());
        }
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_ASR,
                Constants.Ampe.ACTION_DOASR,logLine
                ,jsonObject.toString());
    }



    /**
     *
     * @author xwh
     * Time 2024/11/15
     * Description: 推送语音识别返回的信息
     *
    **/
    private void sendM1toApplet(String info) {
        // 监听，主动推送给小程序
        if (AromeInvoker.getAromeInvoker() != null) {
            AromeInvoker.getAromeInvoker().sendMessageToApplet(Constants.
                    Ampe.ACTION_LISTENER_INIT_ASR,info);
        }

    }

    private void initASRCallBackJson(String event,String data){
        try {
            JsonObject jsonObject =new JsonObject();
            jsonObject.addProperty("event",event);
            jsonObject.addProperty("data",data);
            sendM1toApplet(jsonObject.toString());
        }catch (Exception e){

        }



    }


    public static ASRInvoker getInstance() {
        if (invoker == null) {
            synchronized (ASRInvoker.class) {
                if (invoker == null) {
                    invoker = new ASRInvoker();

                }
            }
        }
        return invoker;
    }

    public void onRelease() {
        AsrSDK.getInstance().release();
        invoker = null;

    }

}
