package com.fzm.mall.customer.service.websocket;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * id：用户id
 */
@ServerEndpoint("/ws/{id}")
@Component
public class WebSocketMsgServer {

    private static Integer ONLINE = 0;

    public static ConcurrentHashMap<String, WebSocketMsgServer> WEBSOCKET_MAP = new ConcurrentHashMap<>();

    private Session session;

    private String userId;

    public static void setApplicationContext(ConfigurableApplicationContext applicationContext) {

    }

    @OnMessage
    public void onMessage(String messageStr) {

    }

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        this.userId = id;
        this.session = session;
        WebSocketMsgServer webSocketServer = WEBSOCKET_MAP.get(this.userId);
        if (webSocketServer == null) {
            WEBSOCKET_MAP.put(this.userId, this);
        }
    }

    @OnClose
    public void onClose(@PathParam("id") String id) {
        WEBSOCKET_MAP.remove(id);
    }

    public static void sendInfo(String id, String message) {
        WebSocketMsgServer msgServer = WEBSOCKET_MAP.get(id);
        if (msgServer != null) {
            msgServer.sendMessage(message);
        }
    }

    private void sendMessage(String message) {
        this.session.getAsyncRemote().sendText(message);
    }
}
