package com.willalp.control.webSocket;

import com.willalp.common.websocket.ServerEncoder;
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.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author xian
 **/
//@ServerEndpoint(value = "/webSocket/{sid}", encoders = {ServerEncoder.class})
//@Component
public class WebSocketServer {
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineNum = new AtomicInteger();
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
     */
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
    Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    /**
     * 发送消息z
     */
    public void sendMessage(Session session, String message) throws IOException, EncodeException {
        if (session != null) {
            synchronized (session) {
                log.info("发送数据：" + message);
                session.getBasicRemote().sendObject(message);
            }
        }
    }

    /**
     * 信息群发
     *
     * @param msg
     */
    public void sendAll(String msg) {
        try {
            for (String key : sessionPools.keySet()) {
                sendMessage(sessionPools.get(key), msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给指定用户发送信息
     *
     * @param userName
     * @param message
     */
    public void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 多个人发送给指定的几个用户
     *
     * @param msg
     * @param persons
     */
    public void SendMany(String msg, String[] persons) {
        try {
            for (String userid : persons) {
                sendMessage(sessionPools.get(userid), msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建立连接成功调用
     *
     * @param session
     * @param userName
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName) {
        sessionPools.put(userName, session);
        addOnlineCount();
        log.info(userName + "加入webSocket！当前人数为" + onlineNum);
        try {
            sendMessage(session, "欢迎" + userName + "加入连接！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接时调用
     *
     * @param userName
     */

    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
        log.info(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    /**
     * 收到客户端信息
     *
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        message = "服务端已收到：" + message;
        log.info(message);
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

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


}
