package com.gyee.frame.common.websocket;

import com.gyee.frame.common.quartz.task.SocketTaskUtil;


import com.gyee.frame.common.spring.InitialRunner;
import com.gyee.frame.util.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class WebSocketCache  extends SocketTaskUtil {

    public static ConcurrentHashMap<String, CopyOnWriteArraySet<String>> websocketcacheMap = new ConcurrentHashMap();

    @EventListener(SessionConnectEvent.class)
    public void onSessionConnectEvent(SessionConnectEvent event) {

        //获取Session连接信息
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());

        List<String> topics=sha.getNativeHeader("topic");
        //获取SessionId
        String sessionId = sha.getSessionId();

       if(StringUtils.isNotEmpty(topics))
       {

           String topic=topics.get(0);

           if(websocketcacheMap.containsKey(topic))
           {
               CopyOnWriteArraySet<String> set=websocketcacheMap.get(topic);
               set.add(sessionId);
               websocketcacheMap.put(topic,set);
           }else
           {
               CopyOnWriteArraySet<String> set= new CopyOnWriteArraySet<String>();
               set.add(sessionId);
               websocketcacheMap.put(topic,set);
           }
           if(InitialRunner.jobsmap.containsKey(topic))
           {
               this.restartJob(topic);
           }
       }


    }


    @EventListener(SessionDisconnectEvent.class)
    public void onDisconnectEvent(SessionDisconnectEvent event) {
        //获取Session连接信息
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        //获取SessionId
        String sessionId = sha.getSessionId();


        String topic= String.valueOf(sha.getNativeHeader("topic"));

        if(StringUtils.isNotEmpty(topic))
        {
            if(websocketcacheMap.containsKey(topic))
            {
                CopyOnWriteArraySet<String> set=websocketcacheMap.get(topic);
                if(set.contains(sessionId))
                {
                    set.remove(sessionId);
                }
                if(set.size()==0)
                {
                    websocketcacheMap.remove(topic);
                }else {
                    websocketcacheMap.put(topic,set);
                    if(InitialRunner.jobsmap.containsKey(topic))
                    {
                        this.restartJob(topic);
                    }
                }

            }
        }

    }

}
