package com.gyee.frame.common.websocket;

import com.gyee.frame.common.quartz.QuartzSchedulerUtil;
import com.gyee.frame.util.StringUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class WebSocketLoginOutEvent extends QuartzSchedulerUtil.SocketTaskUtil {

    public void loginOut(String authToken) {

        if(StringUtils.notEmp(authToken) && !authToken.equals("null"))
        {
            if(WebSocketConfig.sessioncacheMap.containsKey(authToken))
            {
                CopyOnWriteArraySet<String> sessionIdset=WebSocketConfig.sessioncacheMap.get(authToken);

                for(String topic:sessionIdset)
                {
                    if(WebSocketConfig.websocketcacheMap.containsKey(topic))
                    {
                        CopyOnWriteArraySet<String> set=WebSocketConfig.websocketcacheMap.get(topic);
                        set.remove(authToken);
                        WebSocketConfig.websocketcacheMap.put(topic,set);

                        if(set.size()==0)
                        {
                            WebSocketConfig.websocketcacheMap.remove(topic);
                            this.deleteJob(topic);
                        }
                    }

                    sessionIdset.remove(topic);
                }
                WebSocketConfig.sessioncacheMap.remove(authToken);
            }


            if(WebSocketConfig.sessionparamcacheMap.containsKey(authToken))
            {
                CopyOnWriteArraySet<String> sessionIdset=WebSocketConfig.sessionparamcacheMap.get(authToken);

                for(String topic:sessionIdset)
                {
                    if(WebSocketConfig.websocketparamcacheMap.containsKey(topic))
                    {
                        CopyOnWriteArraySet<String> set=WebSocketConfig.websocketparamcacheMap.get(topic);
                        set.remove(authToken);
                        WebSocketConfig.websocketparamcacheMap.put(topic,set);

                        if(set.size()==0)
                        {
                            WebSocketConfig.websocketparamcacheMap.remove(topic);
                            this.deleteJob(topic);
                        }
                    }

                    sessionIdset.remove(topic);
                }
                WebSocketConfig.sessionparamcacheMap.remove(authToken);
            }
        }

    }

}
