package com.ruoyi.system.test;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.IntStream;

/**
 * 2024/4/23
 */
@Component
public class Test {
    public static Map<String, Map<String, Long>> map = new HashMap<>();

    private static final long BIG_TIME = 1000L;

    public static boolean put(String function, String user){
        synchronized (Test.class) {
            long state = System.currentTimeMillis();
            if (map.containsKey(function)){
                Map<String, Long> stringMap = map.get(function);
                if (stringMap.containsKey(user)){
                    Long aLong = stringMap.get(user);
                    if (state - aLong > BIG_TIME){
                        stringMap.put(user, state);
                    }else {
                        stringMap.put(user, state);
                        return false;
                    }
                }else {
                    stringMap.put(user, state);
                }
            }else {
                Map<String, Long> stringMap = new HashMap<>();
                stringMap.put(user, state);
                map.put(function, stringMap);
            }
            return true;
        }
    }

    @Scheduled(fixedRate = 30000)
    public static void expireTime(){
        synchronized (Test.class) {
            long state = System.currentTimeMillis();
            for(Map.Entry<String, Map<String, Long>> m : map.entrySet()){
                Map<String, Long> value = m.getValue();
                if (value == null && value.size() == 0) {
                    map.remove(m.getKey());
                }
                for(Map.Entry<String, Long> mapValue : value.entrySet()){
                    Long v = mapValue.getValue();
                    if (state - v > BIG_TIME){
                        value.remove(mapValue.getKey());
                    }
                }
            }
        }
    }
}