package com.kmall.common.manager.websocket;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Scott Chen
 * @since 1.0
 * 2018-12-24
 */
public class WsInvoker {
    private static final Logger logger = LoggerFactory.getLogger(WsInvoker.class);

    static Map<String, WebSocketClient> clients = new ConcurrentHashMap();

    public static void invoke(String contents, String url, Callback onSuccess, Callback onError) {
        WebSocketClient client = clients.get(url);
        if (client != null && client.isConnecting() && client.isOpen()) {
            client.send(contents);
        } else {
            try {

                client = new WebSocketClient(new URI(url)) {
                    @Override
                    public void onOpen(ServerHandshake handshakedata) {

                    }

                    @Override
                    public void onMessage(String message) {
                        if(onSuccess != null){
                            onSuccess.run(message);
                        }
                    }

                    @Override
                    public void onMessage(ByteBuffer bytes) {
                        try {
                            if(onSuccess != null){
                                onSuccess.run(new String(bytes.array(), "utf-8"));
                            }
                        } catch (UnsupportedEncodingException e) {
                            logger.error("返回不支持的编码消息");
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onClose(int code, String reason, boolean remote) {

                    }

                    @Override
                    public void onError(Exception ex) {
                        if (onError != null) {
                            onError.run(ex);
                        }
                    }
                };

                client.connect();
                Integer timeOut=3*60*1000;
                Integer step=10;
                Integer count=0;

                //阻塞以等待OPEN
                while(!WebSocket.READYSTATE.OPEN.equals(client.getReadyState())){
                    try {
                        count += step;
                        Thread.sleep(step);
                        if(count >= timeOut){
                            onError.run(new Exception("WS服务器连接超时！或服务器已经关闭"));
                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                client.send(contents);
                clients.put(url, client);

            } catch (URISyntaxException e) {
                logger.error("请求url语法错误");
                e.printStackTrace();
            }
        }
    }


}
