package com.hai.service;


import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

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

@Component
@SpringBootTest
@RunWith(SpringRunner.class)
@ServerEndpoint("/WebSocket/{userId}")
public class WebSocket {
    private static Logger log = LoggerFactory.getLogger(WebSocket.class);
    /**
     * 在线用户,将其保存在set中,避免用户重复登录,出现多个session
     */
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> USERS = new ConcurrentHashMap<>();

    //连接时执行
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
        if (userId != null) {
            USERS.put(userId , session);
        }
        System.out.println("【WebSocket消息】有新的连接" + userId);
    }

    //关闭时执行
    @OnClose
    public void onClose() {
        System.out.println("【WebSocket消息】断开连接");
    }

    //收到消息时执行
    @OnMessage
    public void onMessage(String message) throws IOException {
        log.debug("【WebSocket消息】收到客户端发来的信息，总数：{}", message);
    }

    //连接错误时执行
    @OnError
    public void onError(Throwable error) {
        log.debug("【WebSocket消息】收到客户端发来的信息，总数：{}");
        error.printStackTrace();
    }

    // 给制定用户发送信息
    public void SenderMessage(String userId , String message) {
        Session sessionUser = USERS.get(userId);
        try {
            sessionUser.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 断开制定用户
    public void closUser(String userId ) {
        USERS.remove(userId);
        System.out.println("【WebSocket消息】断开连接");
    }

}
