package com.gyee.wisdom.dataadapter.websocket.session;

import com.gyee.wisdom.common.data.timeseries.TsPoint;
import com.gyee.wisdom.dao.timeseries.IDataChangeDao;
import com.gyee.wisdom.dataadapter.domain.topic.TopicService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Data
@Service
public class StompSessionService {

    private HashMap<String, WisdomStompSession> sessionMap = new HashMap<>();
    private Set<String> sessionTopics = new HashSet<>();
    //private boolean isDirtyTopics;

    @Autowired
    private TopicService topicService;

    @Autowired
    private IDataChangeDao dataChangeDao;

    public WisdomStompSession getSession(String sessionId) {
        if (sessionMap.containsKey(sessionId))
            return sessionMap.get(sessionId);

        return null;
    }

    public void addSession(WisdomStompSession session) {
        if (sessionMap.containsKey(session.getSessionId()) == false) {
            sessionMap.put(session.getSessionId(), session);
        }
    }

    public void removeSession(String sessionId) {
        if (sessionMap.containsKey(sessionId))
            sessionMap.remove(sessionId);
    }

    public void subscribeTopic(String sessionId, String topicId) {
        if (sessionMap.containsKey(sessionId)) {
            sessionMap.get(sessionId).subscribeTopic(topicId);
            if (sessionTopics.contains(topicId) == false) {
                sessionTopics.add(topicId);
                List<TsPoint> tsPoints = topicService.getTsPointListByTopic(topicId);
                dataChangeDao.registerTopic(topicId, tsPoints);
            }
        }
    }

    public void unSubscribeTopic(String sessionId, String topic) {
        if (sessionMap.containsKey(sessionId)) {
            sessionMap.get(sessionId).unSubscribeTopic(topic);
            boolean removeTopic = true;
            for (WisdomStompSession session : sessionMap.values() ) {
                if (session.getTopics() != null && session.getTopics().contains(topic)) {
                    removeTopic = false;
                    break;
                }
            }
            if (removeTopic) {
                dataChangeDao.unRegisterTopic(topic);
            }
        }
    }

    public Set<String> getSessionTopics() {
//        if (isDirtyTopics) {
//            refreshSessionTopics();
//            //isDirtyTopics = false;
//        }
        return sessionTopics;
    }



}
