package cn.estsh.i3plus.core.apiservice.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Description : websocket演示，后期移出base
 * @Reference :
 * @Author : alwaysfrin
 * @CreateDate : 2018-09-11 12:32
 * @Modify:
 **/
@ServerEndpoint(value="/demo_websocket/{userName}")
@Component
public class DemoWebSocket {
    private static final Logger LOGGER = LoggerFactory.getLogger(DemoWebSocket.class);

    //在线连接数
    private static int onlineCount = 0;

    //concurrent线程安全集合，存放客户端websocket对象
    private static CopyOnWriteArraySet<DemoWebSocket> webSocketMap = new CopyOnWriteArraySet<DemoWebSocket>();

    //websocket会话
    private Session session;

    @OnOpen
    public void onOpen(@PathParam("userName")String userName, Session session){
        this.session = session;
        webSocketMap.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        LOGGER.info("{}加入！当前在线人数为{}",userName,getOnlineCount());
        try {
            sendMessage(userName + "加入！当前在线人数为" + getOnlineCount());
        } catch (IOException e) {
            LOGGER.info("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketMap.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        LOGGER.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        LOGGER.info("来自客户端的消息:" + message);

        //群发消息
        for (DemoWebSocket item : webSocketMap) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     * @OnError
     */
    @OnError
     public void onError(Session session, Throwable error) {
         LOGGER.info("发生错误");
         error.printStackTrace();
     }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

     /**
      * 群发自定义消息
      * */
    public static void sendInfo(String message) throws IOException {
        for (DemoWebSocket item : webSocketMap) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        DemoWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        DemoWebSocket.onlineCount--;
    }
}
