package cn.reghao.devops.mgr.admin.service;

import cn.reghao.devops.mgr.admin.db.repository.UserRepository;
import cn.reghao.devops.mgr.admin.model.po.User;
import cn.reghao.jutil.jdk.converter.DateTimeConverter;
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;
    }

    // TODO 配置中使用 session.persistent 后, 应用在重启后不能获取到 getLastRequest
    public Map<Integer, String> getLastAccess() {
        Map<Integer, String> map = new HashMap<>();
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            String username = (String) principal;
            User user = userRepository.findByUsername(username);
            for (SessionInformation sessionInfo : sessionRegistry.getAllSessions(principal, false)) {
                try {
                    Date date = sessionInfo.getLastRequest();
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
                    String localDateTimeStr = DateTimeConverter.format(localDateTime);
                    map.put(user.getId(), localDateTimeStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        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();
                    }
                }
            }
        }
    }
}
