package com.yami.shop.seckill.api.socket;

import lombok.extern.slf4j.Slf4j;
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.CopyOnWriteArraySet;

/**
 * @author LGH
 */
@ServerEndpoint("/seckill/websocket/{msgId}")
@Component
@Slf4j
public class WebSocketServer {

    private static final ConcurrentHashMap<String, Session> SESSION_MAP = new ConcurrentHashMap<>(16);

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("msgId") String msgId) {
        log.info("创建连接");
        SESSION_MAP.put(msgId, session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,@PathParam("msgId") String msgId) {
        log.info("关闭连接");
        SESSION_MAP.remove(msgId);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session,@PathParam("msgId") String msgId, Throwable error) {
        SESSION_MAP.remove(msgId);
        log.error("发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public static void sendMessage(String msgId, String message) {
        Session session = SESSION_MAP.get(msgId);
        if (session == null) {
            return;
        }
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
