package cn.com.poc.thirdparty.resource.simultanous_interpretation.api;

import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.http.LocalHttpClient;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.AsrOfflineDetailResult;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.GetDetailResult;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.SpeechToTextResult;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.google.gson.Gson;
import okhttp3.*;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 语音识别接口
 */
@Component
public class ASRApi {

    private final Logger logger = LoggerFactory.getLogger(ASRApi.class);

    @Value("${simultanous_interpretation.endpoint}")
    private String ENDPOINT;

    private String SPEECH_TO_TEXT_API = "/api/rest/asrRest/speechToText.json";

    private String GET_DETAIL_API = "/api/rest/asrRest/getDetail.json";

    public final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
            .readTimeout(15, TimeUnit.SECONDS)
            .build();

    /**
     * 语音识别 / 离线文件
     *
     * @param sessionId 唯一主键ID 长度不超过200位字符
     * @param file      音频文件 不超过500M
     * @return "success"提交成功
     */
    public SpeechToTextResult speechToText(String sessionId, File file) {
        Assert.notBlank(sessionId);
        Assert.notNull(file);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        try {
            RequestBody baseFile = RequestBody.create(MediaType.parse(Objects.requireNonNull(Files.probeContentType(file.toPath()))), file);
            builder.addFormDataPart("sessionId", sessionId);
            builder.addFormDataPart("audio", file.getName(), baseFile);
            MultipartBody body = builder.build();
            Request request = new Request.Builder()
                    .url(ENDPOINT + SPEECH_TO_TEXT_API)
                    .method("POST", body)
                    .addHeader("Content-Type", "multipart/form-data")
                    .build();
            String result = Objects.requireNonNull(HTTP_CLIENT.newCall(request).execute().body()).string();
            Gson gson = new Gson();
            return gson.fromJson(result, SpeechToTextResult.class);
        } catch (IOException e) {
            logger.error("调用ASR失败", e);
            throw new BusinessException("调用ASR失败");
        }
    }

    /**
     * 获取离线语音识别状态
     *
     * @param sessionId 唯一主键
     * @return
     */
    public GetDetailResult getDetail(String sessionId) {
        Assert.notBlank(sessionId);
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setUri(ENDPOINT + GET_DETAIL_API + "?sessionId=" + sessionId)
//                .addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()))
//                .addParameter("sessionId", sessionId)
                .build();
        return LocalHttpClient.executeJsonResult(httpUriRequest, GetDetailResult.class);
    }
}
