package cn.reghao.oss.console.account.service;

import cn.reghao.oss.console.account.db.repository.UserRepository;
import cn.reghao.oss.console.account.model.po.User;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author reghao
 * @date 2024-02-04 16:00:01
 */
@Service
public class AccountSessionService {
    private final SessionRegistry sessionRegistry;
    private final UserRepository userRepository;

    public AccountSessionService(SessionRegistry sessionRegistry, UserRepository userRepository) {
        this.sessionRegistry = sessionRegistry;
        this.userRepository = userRepository;
    }

    public Map<Integer, LocalDateTime> getLastRequest() {
        Map<Integer, LocalDateTime> map = new HashMap<>();
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            String username = (String) principal;
            User user = userRepository.findByUsername(username);
            for (SessionInformation sessionInfo : sessionRegistry.getAllSessions(principal, false)) {
                Date date = sessionInfo.getLastRequest();
                LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
                map.put(user.getId(), localDateTime);
            }
        }

        return map;
    }

    public void deactiveSession(User user) {
        int currentUserId = UserContext.getUser().getId();
        if (currentUserId != user.getId()) {
            String principal = user.getUsername();
            for (Object object : sessionRegistry.getAllPrincipals()) {
                String username = (String) object;
                if (username.equals(principal)) {
                    for (SessionInformation sessionInfo : sessionRegistry.getAllSessions(principal, false)) {
                        sessionInfo.expireNow();
                    }
                }
            }
        }
    }
}
