package com.sonic.cow.controller.web;

import com.mashape.unirest.http.exceptions.UnirestException;
import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.cow.domain.input.VoiceAsrInput;
import com.sonic.cow.domain.input.VoiceTtsV2Input;
import com.sonic.cow.domain.output.AsrOutput;
import com.sonic.cow.limit.RequestLimit;
import com.sonic.cow.service.VoiceService;
import com.sonic.cow.service.VoiceV2Service;
import com.sonic.cow.utils.Base64Utils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * Web-语音处理
 */
@RestController
@Slf4j
public class VoiceWeb {

    @Autowired
    private VoiceService voiceService;
    @Autowired
    private VoiceV2Service voiceV2Service;

    @RequestLimit(count = 100, time = 86400000)
    @ApiOperation(value = "语音转文本V3版本", tags = {"Web-语音处理"})
    @PostMapping(value = "/web/voice/asr-v3")
    public Result<AsrOutput> asrV3(@RequestBody VoiceAsrInput input, @ApiParam(hidden = true) Session session, @ApiParam(hidden = true) HttpServletRequest request) throws UnirestException {
        //保存到临时 File
        String suffix = StringUtils.isEmpty(input.getSuffix()) ? ".mp3" : input.getSuffix();
        File tempFile = Base64Utils.decodeToTempFile(input.getData(), UUID.randomUUID() + suffix);
        return Result.success(voiceV2Service.asr(session.getUserId(), input.getAiId(), tempFile));
    }

    @RequestLimit(count = 100, time = 86400000)
    @ApiOperation(value = "生成语音V2版本", tags = {"Web-语音处理"})
    @PostMapping(value = "/web/voice/tts-v2")
    public Result<String> ttsV2(@RequestBody VoiceTtsV2Input input, @ApiParam(hidden = true) Session session, @ApiParam(hidden = true) HttpServletRequest request) {
        return Result.success(voiceService.tts(session.getUserId(), input));
    }

}
