package com.yeejoin.amos.speech;

import okhttp3.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;

/**
 * 不支持免费用户测试
 * 录音文件识别极速版（支持提交音频文件识别，文件大小，文件时长有限制）
 * <p>
 * 音频格式：支持AAC/MP3/OPUS/WAV格式编码的音频。
 * 使用限制：支持100 MB以内且不超过2小时的音频文件的识别。
 *
 * @see SpeechRecognizer
 * 时长超过2小时的文件请使用录音文件识别普通版
 *
 * <p>
 * 模型类型：8000（电话）/16000（非电话）。
 * <p>
 * 同步返回识别结果
 */
public class SpeechFlashRecognizer {
    private static final Logger logger = LoggerFactory.getLogger(SpeechFlashRecognizer.class);
    //音频文件
    private final File speechFile;
    //音频格式
    private final String format;
    //音频采样率
    private final int sampleRate;
    //识别回调函数
    private final Callback callback;


    public SpeechFlashRecognizer(File speechFile, int sampleRate, Callback callback) {
        if (speechFile == null || !speechFile.exists() || !speechFile.isFile()) {
            throw new IllegalArgumentException("待识别的文件存在异常");
        }
        if (sampleRate == 0) {
            throw new IllegalArgumentException("音频采样率不能为0");
        }
        String[] split = speechFile.getName().split("\\.");
        if (split.length != 0) {
            this.format = split[split.length - 1];
        } else {
            throw new IllegalArgumentException("音频文件格式提取失败");
        }
        this.speechFile = speechFile;
        this.sampleRate = sampleRate;
        this.callback = callback;
    }

    /**
     * 设置HTTPS REST POST请求
     * 1.使用http协议
     * 2.语音识别服务域名：nls-gateway.cn-shanghai.aliyuncs.com
     * 3.语音识别接口请求路径：/stream/v1/FlashRecognizer
     * 4.设置必须请求参数：appkey、token、format、sample_rate
     * 5.Content-Type 类型必须为 application/octet-stream
     */
    public void process() {
        String request = "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/FlashRecognizer";
        request = request + "?appkey=" + SpeechConfig.AppKey;
        request = request + "&token=" + AppNslClientToken.instance().getToken();
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + sampleRate;
        logger.info("Request: " + request);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/octet-stream");
        AppOkHttpClient.sendPostFile(request, headers, this.speechFile, this.callback);
    }
}
