package com.imdroid.beidou.controller;

import com.imdroid.beidou.config.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//单例

@ServerEndpoint(value = "/websocket",configurator = WebSocketConfig.class)
@Component
@Slf4j
public class WebSocketServer {
    // thread safety counter
    // thread safety set to hold websocket objects
    private static Map<String,Session> webSocketSet = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session){
        HttpSession httpSession= (HttpSession) session.getUserProperties().get(HttpSession.class.getName());
        webSocketSet.put(httpSession.getId(), session);
        log.info("new websocket opened, total socket num: "+ webSocketSet.size());
    }

    @OnClose
    public void onClose(Session session){
        HttpSession httpSession= (HttpSession) session.getUserProperties().get(HttpSession.class.getName());
        if(httpSession!=null) {
            webSocketSet.remove(httpSession.getId());
        }
        log.info("websocket closed, total socket num: "+ webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String msg, Session session){
        //log.info("websocket: "+msg);
    }

    @OnError
    public void onError(Session session, Throwable error){
        error.printStackTrace();
    }

    public static void sendMessageToAll(String msg){
        try {
            for (Session item : webSocketSet.values()) {
                item.getBasicRemote().sendText(msg);
            }
        }
        catch (Exception e){
            log.error("websocket send msg error:", e);
        }
    }

    public static void sendMessage(HttpSession httpSession, String msg) {
        Session session = webSocketSet.get(httpSession.getId());
        if(session != null){
            try {
                session.getBasicRemote().sendText(msg);
            }
            catch (Exception e){
                log.error("websocket send msg error:", e);
            }
        }
    }

}
