package com.xhly.websocket.service;

import android.util.Log;

import com.neovisionaries.ws.client.WebSocket;
import com.xhly.corelib.utils.GsonUtils;
import com.xhly.websocket.bean.HertBean;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WebSocketHelper {

    private static final WebSocketHelper ourInstance = new WebSocketHelper();
    private final ExecutorService sendExecutor = Executors.newSingleThreadExecutor();
    private WebSocket webSocket;

    private WebSocketHelper() {
    }

    public static WebSocketHelper getInstance() {
        return ourInstance;
    }

    public WebSocketHelper build(WebSocket webSocket) {
        this.webSocket = webSocket;
        return this;
    }

    /**
     * @param type 发送不同的type获得socket内容
     */
    public void sendSocketType(String type) {
        HertBean hertBean = new HertBean();
        hertBean.setType(type);
        String s = GsonUtils.parseClassToJson(hertBean);
        send(webSocket, s);
    }

    public void sendSocketString(String s) {
        send(webSocket, s);
    }

    /**
     * @param webSocket
     * @param id        心跳
     */
    public void hearBeat(WebSocket webSocket) {
        /*HertBean hertBean = new HertBean();
        hertBean.setType("ping");
        String s = GsonUtils.parseClassToJson(hertBean);
        send(webSocket, s);*/
        if (webSocket == null) {
            return;
        }
        sendExecutor.execute(new Runnable() {
            @Override
            public void run() {
                byte[] byteArray = new byte[1];
                webSocket.sendBinary(byteArray);
            }
        });
    }

    private void send(final WebSocket webSocket, final String data) {
        Log.v("socket", "socket 发送消息：" + data);
        if (webSocket == null) {
            return;
        }
        sendExecutor.execute(new Runnable() {
            @Override
            public void run() {
                webSocket.sendText(data);
            }
        });
    }


}