package com.nokia.hb.service;

import com.github.benmanes.caffeine.cache.Cache;
import com.nokia.hb.config.CacheConfig;
import com.nokia.hb.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@Service
public class SessionService {
    private final CacheConfig cacheConfig;
    private final Cache<String, Object> sessionCache;

    public SessionService(CacheConfig cacheConfig, Cache<String, Object> sessionCache) {
        this.cacheConfig = cacheConfig;
        this.sessionCache = sessionCache;
    }

    /**
     * 更新
     *
     * @param session 会话
     */
    public void update(HttpSession session) {
        session.setMaxInactiveInterval(cacheConfig.getTimeout());
        String username = SessionUtil.getUsername(session);
        log.info("{} last login at {}", username, sessionCache.get(username, k -> LocalDateTime.now()));
    }

    /**
     * 是否已经登录过
     *
     * @param username 用户名
     * @return boolean
     */
    public boolean logged(String username) {
        return sessionCache.getIfPresent(username) != null;
    }

    /**
     * 失效
     *
     * @param session 会话
     */
    public void invalidate(HttpSession session) {
        String username = SessionUtil.getUsername(session);
        session.invalidate();
        sessionCache.invalidate(username);
    }
}
