package com.yeejoin.amos.boot.module.jcs.biz.audioToText.streamToText;

import com.yeejoin.amos.boot.module.jcs.biz.audioToText.AudioKeyWord;
import com.yeejoin.amos.boot.module.jcs.biz.audioToText.AudioRecord;
import com.yeejoin.amos.boot.module.jcs.biz.audioToText.RealTimeSpeechTranscriberListener;
import com.yeejoin.amos.speech.AppSpeechTranscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 实时语音转文字
 */
@Component
public class RealTimeStream2Text {
    private static final Logger logger = LoggerFactory.getLogger(RealTimeStream2Text.class);
    public static int serverPort = 25000;

    @Autowired
    EmqKeeper emqKeeper;

    @Autowired
    RestTemplate restTemplate;

    @Value("${ifc.url}")
    String audioSystemAddress;

    @Value("${ifc.call-back.localIp}")
    String localIpAddress;

    /**
     * 开始语音转文字
     *
     * @param myNumber     我的电话号码
     * @param callerNumber 呼入电话号码
     */
    public HashMap<String, Object> doTranslate(String cid, String myNumber, String callerNumber) {
        //启动两个监听端口监听推送进来的2路语音流
        DatagramSocket serverSocket1 = initServerSocketPort();
        DatagramSocket serverSocket2 = initServerSocketPort();
        //识别的记录
        List<AudioRecord> audioRecords = new ArrayList<>();
        //识别的关键字
        AudioKeyWord audioKeyWord = new AudioKeyWord();
        logger.warn("myNumber监听的端口为：" + serverSocket1.getLocalPort() + "  callerNumber监听的端口为：" + serverSocket2.getLocalPort());
        //我的语音流
        Thread thread1 =
                new Thread(() -> {
                    new AppSpeechTranscriber(
                            new RealTimeSpeechTranscriberListener(myNumber, myNumber, emqKeeper, audioRecords, audioKeyWord),
                            serverSocket1, localIpAddress)
                            .process();
                }, "我的语音流");
        //呼入的语音流
        Thread thread2 =
                new Thread(() -> {
                    new AppSpeechTranscriber(
                            new RealTimeSpeechTranscriberListener(myNumber, callerNumber, emqKeeper, audioRecords, audioKeyWord),
                            serverSocket2, localIpAddress)
                            .process();
                }, "呼入的语音流");
        thread1.setUncaughtExceptionHandler(new SubUncaughtExceptionHandler(serverSocket1));
        thread2.setUncaughtExceptionHandler(new SubUncaughtExceptionHandler(serverSocket2));
        thread1.start();
        thread2.start();
        startNotifyAudioStreamSystem(cid, myNumber, serverSocket1.getLocalPort());
        startNotifyAudioStreamSystem(cid, callerNumber, serverSocket2.getLocalPort());
        HashMap<String, Object> map = new HashMap<>();
        map.put(myNumber, serverSocket1.getLocalPort());
        map.put(callerNumber, serverSocket2.getLocalPort());
        return map;
    }

    /**
     * @param cid    会议ID
     * @param number 需要的号码的音频流
     * @param port   推流端口
     */
    @Async
    public void startNotifyAudioStreamSystem(String cid, String number, int port) {
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("cid", cid);
            map.add("number", number);
            map.add("codec", "PCM");
            map.add("uuid", UUID.randomUUID().toString());
            map.add("dstip", localIpAddress);
            map.add("dstport", String.valueOf(port));
            map.add("marker", "amos");
            httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<LinkedMultiValueMap<String, Object>> linkedMultiValueMapHttpEntity = new HttpEntity<>(map, httpHeaders);
            ResponseEntity<AudioResponseEntity> audioResponseEntity = restTemplate.postForEntity(
                    audioSystemAddress + "/StartPushingVoiceStream", linkedMultiValueMapHttpEntity, AudioResponseEntity.class);
            AudioResponseEntity responseEntityBody = audioResponseEntity.getBody();
            if (responseEntityBody == null) {
                logger.error("调用语音融合系统接口获取音频流返回异常：响应体为空");
                return;
            }
            if (responseEntityBody.getState() == 200) {
                logger.warn("调用语音融合系统接口获取音频流返回正常：结果：" + responseEntityBody.toString());
            } else {
                logger.error("调用语音融合系统接口获取音频流返回异常：响应码：" + responseEntityBody.getState());
                logger.error("调用语音融合系统接口获取音频流返回异常：失败原因：" + responseEntityBody.getDescribe());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

    /**
     * 获取一个ServerSocket
     */
    private DatagramSocket initServerSocketPort() {
        while (true) {
            try {
                return new DatagramSocket(serverPort);
            } catch (SocketException exception) {
                serverPort++;
                if (serverPort == 27999) serverPort = 25000;
            }
        }
    }

    /**
     * 线程抛出异常，关闭监听端口，防止端口未安全关闭
     */
    static class SubUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
        private static final Logger logger = LoggerFactory.getLogger(SubUncaughtExceptionHandler.class);
        DatagramSocket serverSocket;

        public SubUncaughtExceptionHandler(DatagramSocket serverSocket) {
            this.serverSocket = serverSocket;
        }

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
                logger.error("子线程出现异常，已关闭音频监听端口。" + e.getMessage());
            }
        }
    }

    /**
     * 语音融合系统响应体
     */
    static class AudioResponseEntity {
        private int state;
        private String describe;
        private Object data;

        public int getState() {
            return state;
        }

        public void setState(int state) {
            this.state = state;
        }

        public String getDescribe() {
            return describe;
        }

        public void setDescribe(String describe) {
            this.describe = describe;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "AudioResponseEntity{" +
                    "state=" + state +
                    ", describe='" + describe + '\'' +
                    ", data=" + data +
                    '}';
        }
    }
}
