package com.ruoyi.framework;

import com.ruoyi.common.constant.CacheConstants;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;

@Component
public class OnlineUserTodayCache {

    @Autowired
    private RedissonClient redissonClient;

    private String getKey(LocalDate dateTime){
        String today = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        return  String.format(CacheConstants.ONLINE_TODAY_TOKEN_KEY,today);
    }

    public boolean addOnlineUserId(Long userId, LocalDate dateTime){
        RSet<Long> set = redissonClient.getSet(getKey(dateTime));
        boolean res = set.add(userId);
        set.expire(Duration.ofDays(3));
        return res;
    }

    public Set<Long> getAllOnlineToday(){
        RSet<Long> set = redissonClient.getSet(getKey(LocalDate.now()));
        return set.readAll();
    }

    public Long getOnlineNum(LocalDate time){
        RSet<Long> set = redissonClient.getSet(getKey(time));
        return (long) set.size();
    }

    public Long getOnlineTodayNum(){
        RSet<Long> set = redissonClient.getSet(getKey(LocalDate.now()));
        return (long) set.size();
    }

    public Long getOnlineLastNum(){
        RSet<Long> set = redissonClient.getSet(getKey(LocalDate.now().plusDays(-1)));
        return (long) set.size();
    }
}
