package com.gyee.frame.common.websocket;

import com.gyee.frame.common.quartz.QuartzSchedulerUtil;
import com.gyee.frame.util.StringUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket建立链接的时候获取headeri里认证的参数拦截器。
 */
@Component
public class ClientInboundChannelInterceptor extends QuartzSchedulerUtil.SocketTaskUtil implements ChannelInterceptor {


    private String AUTHTOKEN="authToken";
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);

            String topic=null;
            String authToken=null;
            if (raw instanceof Map) {
                Object name = ((Map) raw).get("topic");
                LinkedList<String> temp=(LinkedList<String>) name;
                topic=temp.get(0);
                Object authTokenobj = ((Map) raw).get("authToken");
                 temp=(LinkedList<String>) authTokenobj;
                authToken=temp.get(0);
            }
            //String authToken =String.valueOf(message.getHeaders().get(SimpMessageHeaderAccessor.SESSION_ID_HEADER));

           // String authToken =String.valueOf(message.getHeaders().get(AUTHTOKEN));
            if(StringUtils.notEmp(topic) && !topic.equals("undefined") && StringUtils.notEmp(authToken) && !authToken.equals("undefined")) {


                //判断是否为带参操作
                if(topic.indexOf(WebSocketConfig.PARAM)!=-1)
                {
                    if (StringUtils.notEmp(authToken)) {
                        //判断带参sessionMAP中是否包含authToken
                        if (WebSocketConfig.sessionparamcacheMap.containsKey(authToken)) {
                            //通过sessionId获得topicSET集合
                            CopyOnWriteArraySet<String> set = WebSocketConfig.sessionparamcacheMap.get(authToken);
                            //截取topic/****/中的功能描述
                            String temptoptic=topic.substring(topic.indexOf("/")+1);
                            temptoptic=temptoptic.substring(0,temptoptic.indexOf("/"));
                            //遍历SET中的主体
                            for(String str:set)
                            {
                                //截取str/****/中的功能描述
                                String tempstr=str.substring(str.indexOf("/")+1);
                                tempstr=tempstr.substring(0,tempstr.indexOf("/"));
                                //判断str的功能描述和topic的功能描述是否一致
                                if(temptoptic.equals(tempstr))
                                {
                                    //功能描述一致，移除相同功能的主题，保证每个sessionid相同功能只能通过传参订阅一个主题
                                    set.remove(str);
                                    //提供过str主题获得sessionidSET集合
                                    CopyOnWriteArraySet<String> sessionIdset = WebSocketConfig.websocketparamcacheMap.get(str);
                                    //移除主题中的sessionId
                                    sessionIdset.remove(authToken);
                                    //如果sessionIdset记录为空，移除websocketparamcacheMap的主题
                                    if(sessionIdset.size()==0)
                                    {
                                        WebSocketConfig.websocketparamcacheMap.remove(str);
                                    }

                                }
                            }
                            //添加新的主题
                            set.add(topic);
                            WebSocketConfig.sessionparamcacheMap.put(authToken, set);
                        } else {
                            CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>();
                            set.add(topic);
                            WebSocketConfig.sessionparamcacheMap.put(authToken, set);
                        }


                    }

                    if (WebSocketConfig.websocketparamcacheMap.containsKey(topic)) {
                        CopyOnWriteArraySet<String> set = WebSocketConfig.websocketparamcacheMap.get(topic);
                        set.add(authToken);
                        WebSocketConfig.websocketparamcacheMap.put(topic, set);
                    } else {
                        CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>();
                        set.add(authToken);
                        WebSocketConfig.websocketparamcacheMap.put(topic, set);
                    }
                }else
                {
                    if (WebSocketConfig.websocketcacheMap.containsKey(topic)) {
                        CopyOnWriteArraySet<String> set = WebSocketConfig.websocketcacheMap.get(topic);
                        set.add(authToken);
                        WebSocketConfig.websocketcacheMap.put(topic, set);
                    } else {
                        CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>();
                        set.add(authToken);
                        WebSocketConfig.websocketcacheMap.put(topic, set);
                    }


                    if (StringUtils.notEmp(authToken)) {
                        if (WebSocketConfig.sessioncacheMap.containsKey(authToken)) {
                            CopyOnWriteArraySet<String> set = WebSocketConfig.sessioncacheMap.get(authToken);
                            set.add(topic);
                            WebSocketConfig.sessioncacheMap.put(authToken, set);
                        } else {
                            CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>();
                            set.add(topic);
                            WebSocketConfig.sessioncacheMap.put(authToken, set);
                        }


                    }
                }


                if(topic.indexOf(WebSocketConfig.PARAM)!=-1)
                {

//                    String wtid=topic.substring(topic.indexOf(PARAM)+6);
                    topic=topic.substring(0,topic.indexOf("_"));
                    this.restartJob(topic);
                }else
                {
                    this.restartJob(topic);
                }

            }

        }
        return message;
    }
}