package net.northking.cctp.mobile.util;

import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.CloseReason;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class WSUtils {
    private static final Logger logger = LoggerFactory.getLogger(WSUtils.class);


    public static void sendText(RemoteEndpoint.Basic remoteEndpoint, String msg, String deviceId) {
        try {
            remoteEndpoint.sendText(msg);
        } catch (IOException e) {
            logger.warn("web端session已经断开",e);
        }

    }


    public static void sendBytes(RemoteEndpoint.Basic basicRemote, ByteBuffer data, String deviceId) {
        try {
            basicRemote.sendBinary(data);
        } catch (IOException e) {
            logger.warn("web端session已经断开",e);
        }
    }

    public static void sendText(Session session, String msg, String deviceId) {
        synchronized (session) {
            if (null != session && session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(msg);
                } catch (Exception e) {
                    logger.error(String.format("设备【%s】发送屏幕数据到前端失败", deviceId), e);
                    //增加重发机制
                }
            } else {
                logger.warn("Session[deviceId:{}]不存在或已关闭...", deviceId);
                //关闭上位机会话
                try {
                    session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "session失效关闭"));
                } catch (IOException e) {
                    logger.warn("session关闭失败", e);
                }
                return;
            }
        }

    }
}
