package com.xinelu.common.socket;

import com.alibaba.fastjson2.JSON;
import com.xinelu.common.core.dto.MessageTemplate;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.Session;
import lombok.extern.slf4j.Slf4j;

/**
 * shitianqi
 * 2022-01-18 19:17
 * socket类和请求和方法
 */
@Slf4j
public class WebSocketUtils {


    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    /**
     * 记录当前在线连接数
     */
    public static AtomicInteger onlineCount = new AtomicInteger();

    /**
     * 存放所有在线的客户端
     */
    public static ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 上线用户 <br/>
     *
     * @param key
     * @param session
     */
    public static void add(String key, Session session) throws IOException {
        remove(key);
        clients.put(key, session);
        onlineCount.incrementAndGet(); // 在线数加1
        int count = onlineCount.get();
        log.info("有新连接加入：{}，当前在线人数为：{}", key, count > 0? count: 0);
    }


    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 打印某在线用户接收消息内容和在线情况到日志 <br/>
     *
     * @param key
     * @param message
     */
    public static void receive(String key, String message) {
        log.info("服务端收到客户端[{}]的消息:{}", key, message);
//        log.info("当前连接数 = " + clients.size());
    }

    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 下线用户 <br/>
     *
     * @param key
     */
    public static void remove(String key) throws IOException {
        if (clients.containsKey(key)) {
            clients.get(key).close();
            clients.remove(key);
            onlineCount.decrementAndGet(); // 在线数减1
//            log.info("有一连接关闭：{}，当前在线人数为：{}", key, onlineCount.get());
        }
//        log.info("当前连接数 = " + clients.size());
    }

    /**
     * shitianqi <br/>
     * 2022-01-18 19:47 <br/>
     * 发送消息（内容为对象json） <br/>
     *
     * @param key
     * @param msg
     * @return boolean 是否成功
     */
    public static boolean sendMessage(String key, MessageTemplate msg) {
//        log.info("当前连接数 = " + clients.size());
        if (clients.get(key) == null) {
            return false;
        } else {
            try {
                log.info("发送消息：" + JSON.toJSONString(msg));
                clients.get(key).getBasicRemote().sendText(JSON.toJSONString(msg));
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }
}
