package com.turing.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.StringUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.ByteBuffer;

/**
 * ws协议请求tts协议
 */
public class TtsWsDemo {

    // NLP文本
    public static final String TEXT = "欢迎来到图灵平台。";

    // 地址
    public static final String hostUrl = "ws://ws-api.turingapi.com/api/v2";
    // 均到biz的机器人信息页面获取
    public static final String apiSecret = "11F******oC";
    public static final String apiKey = "c1b7**********16bc318aed";
    public static final String deviceId = "12332323";


    public static boolean wsCloseFlag = false;
    public static final String OUTPUT_FILE_PATH = "d://";
    static OutputStream outputStream=null;

    public static void main(String[] args) throws Exception {
        websocketWork(hostUrl);
    }

    // Websocket方法
    public static void websocketWork(String wsUrl) {
        try {
            URI uri = new URI(wsUrl);
            WebSocketClient webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println("ws建立连接成功...");
                }

                @Override
                public void onMessage(String text) {
                    //服务器相应文本内容
                    System.err.println(text);
                    JSONObject object=JSONObject.parseObject(text);
                    String ttsStreamId=null;
                    if (object.getInteger("code")==200){
                        JSONArray results=object.getJSONObject("nlpResponse").getJSONArray("results");
                        for (int i=0;i<results.size();i++){
                            //非流示解析
//                            JSONArray ttsUrls= results.getJSONObject(i).getJSONObject("values").getJSONArray("ttsUrl");
                            //输出多个音频url链接
//                            System.out.println(ttsUrls.toJSONString());
                            // 可以关闭连接，释放资源
//                            wsCloseFlag = true;

                            //流式解析
                            ttsStreamId=results.getJSONObject(i).getJSONObject("values").getString("ttsStreamId");
                            try {
                                outputStream = new FileOutputStream(OUTPUT_FILE_PATH+ttsStreamId+".pcm");

                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if (object.getInteger("code")==260){
                        int state=object.getJSONObject("ttsResponse").getInteger("state");
                        String binarysId=object.getJSONObject("ttsResponse").getString("binarysId");
                        if (state==200 && StringUtils.equals(binarysId,ttsStreamId)){
                            try {
                                outputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            // 可以关闭连接，释放资源
                            wsCloseFlag = true;
                        }
                    }

                }
                @Override
                public void onMessage(ByteBuffer bytes) {
                    //服务器返回的字节流
                    try {
                        outputStream.write(bytes.array());
                        outputStream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
                @Override
                public void onClose(int i, String s, boolean b) {
                    System.out.println("ws链接已关闭，本次请求完成...");
                }

                @Override
                public void onError(Exception e) {
                    System.out.println("发生错误 " + e.getMessage());
                }
            };
            // 建立连接
            webSocketClient.connect();
            while (!webSocketClient.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                //System.out.println("正在连接...");
                Thread.sleep(100);
            }

            MyThread webSocketThread = new MyThread(webSocketClient, requestText(TEXT));
            webSocketThread.start();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }


    }

    public static String requestText(String input) {
        //请求参数json串
        String requestJson = "{" +
                "    \"key\":\""+apiKey+"\"," +
                "    \"timestamp\":\"1585799006000\"," +
                "    \"data\":{" +
                "        \"deviceId\":\""+deviceId+"\"," +
                "        \"requestType\":[" +
                "            2" +
                "        ]," +
                "        \"nlpRequest\":{" +
                "            \"content\":[" +
                "                {" +
                "                    \"data\":\""+input+"\"" +
                "                }" +
                "            ]," +
                "       \"clientInfo\":{" +
                "           \"robotSkill\":{" +
                "              \"50101\":{" +
                "                    \"config\":{" +
                "                        \"tone\":\"aq\"," +
                "                        \"speed\":5," +
                "                        \"format\":\"PCM_16_16\"," +
                "                        \"volume\":5," +
                "                        \"pitch\": 5," +
                "                        \"arousal\": 5" +
                "                     }" +
                "                  }" +
                "              }" +
                "           }" +
                "        }," +
                "       \"streamTts\":true" +
                "    }" +
                "}";
        return requestJson;
    }

    // 线程来发送音频与参数
    static class MyThread extends Thread {
        WebSocketClient webSocketClient;
        String sendMessage;

        public MyThread(WebSocketClient webSocketClient, String sendMessage) {
            this.webSocketClient = webSocketClient;
            this.sendMessage = sendMessage;
        }

        public void run() {
            try {
                webSocketClient.send(sendMessage);
                // 等待服务端返回完毕后关闭
                while (!wsCloseFlag) {
                    Thread.sleep(200);
                }
                webSocketClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



}
