package com.rf.psychological.module.online.listener;

import com.alibaba.fastjson.JSON;
import com.rf.psychological.user.dao.model.UserEntity;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;

/**
 * @author lpf
 * @description:
 * @date 2022/6/8 11:26
 */
@WebListener
@Slf4j
public class OnlineUserListener implements HttpSessionListener, HttpSessionAttributeListener {

    private HashMap<String, Long> onlineUserCount = new HashMap<>();

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        log.info("HttpSessionListener监听session创建");
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        String addSessionName = se.getName();
        if ("user".equals(addSessionName)) {
            UserEntity user = (UserEntity) se.getValue();
            if (user != null) {
                if (onlineUserCount.containsKey(user.getInstitutionNo())) {
                    Long count = onlineUserCount.get(user.getInstitutionNo());
                    count++;
                    onlineUserCount.put(user.getInstitutionNo(), count);
                } else {
                    onlineUserCount.put(user.getInstitutionNo(), 1L);
                }
            }
        }
        log.info("HttpSessionListener监听器" + JSON.toJSONString(onlineUserCount));
        se.getSession().getServletContext().setAttribute("onlineUserCount", onlineUserCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        log.info("HttpSessionListener监听session销毁");
        UserEntity user = (UserEntity) se.getSession().getAttribute("user");
        if (user != null) {
            if (onlineUserCount.containsKey(user.getInstitutionNo())) {
                Long count = onlineUserCount.get(user.getInstitutionNo());
                if (count != 0L) {
                    count--;
                } else {
                    count = 0L;
                }
                onlineUserCount.put(user.getInstitutionNo(), count);
            }
        }
        se.getSession().getServletContext().setAttribute("onlineUserCount", onlineUserCount);
    }

}
