package com.kingdee.eas.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 带过期时间的Map
 *
 * @param <K>
 * @param <V>
 */
public class ExpiringMapCache<K, V> {
    private final Map<K, CacheValue<V>> cache = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public ExpiringMapCache() {
        scheduler.scheduleAtFixedRate(() -> {
            long currentTime = System.currentTimeMillis();
            cache.entrySet().removeIf(entry -> currentTime >= entry.getValue().expiryTime);
        }, 1, 1, TimeUnit.SECONDS); // 每秒检查过期
    }

    public void put(K key, V value, long durationInMillis) {
        long expiryTime = System.currentTimeMillis() + durationInMillis;
        cache.put(key, new CacheValue<>(value, expiryTime));
    }

    public V get(K key) {
        CacheValue<V> cacheValue = cache.get(key);
        if (cacheValue != null && System.currentTimeMillis() < cacheValue.expiryTime) {
            return cacheValue.value;
        }
        cache.remove(key); // 删除已过期的条目
        return null;
    }

    public void shutdown() {
        scheduler.shutdown();
    }

    private static class CacheValue<V> {
        private final V value;
        private final long expiryTime;

        public CacheValue(V value, long expiryTime) {
            this.value = value;
            this.expiryTime = expiryTime;
        }
    }
}

