package ru.ulstu.user.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.user.model.UserSession;
import ru.ulstu.user.repository.UserSessionRepository;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
public class UserSessionScheduler {
    private final Logger log = LoggerFactory.getLogger(UserSessionScheduler.class);

    private final UserSessionRepository userSessionRepository;

    public UserSessionScheduler(UserSessionRepository userSessionRepository) {
        this.userSessionRepository = userSessionRepository;
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void closeOldSessions() {
        log.debug("UserSessionScheduler.closeOldSessions started");
        final List<UserSession> sessions = userSessionRepository.findAllByLogoutTimeIsNullAndLoginTimeBefore(
                DateUtils.instantToDate(Instant.now().minus(1, ChronoUnit.DAYS)));
        sessions.forEach(session -> {
            log.debug("Close session {}", session.getSessionId());
            session.close();
            userSessionRepository.save(session);
        });
        log.debug("UserSessionScheduler.closeOldSessions finished");
    }
}
