package com.bcxin.tenant.open.domains.components;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

public class HotCacheManager {
    private static final Logger logger = LoggerFactory.getLogger(HotCacheManager.class);
    private static final Cache<String, Object> _hotCache = Caffeine.newBuilder()
            .maximumSize(100)
            .softValues()
            .expireAfterWrite(10, TimeUnit.MINUTES).build();

    public static <T> void put(CacheDataType dataType, String key, T data) {
        try {
            getMatchCache(dataType).put(getCacheKey(dataType, key), data);
        } catch (Exception ex) {
            logger.error("存储缓存数据发生异常:{}",getCacheKey(dataType, key), ex);
        }
    }

    public static <T> T get(CacheDataType dataType,String key) {
        try {
            return null;
            //return (T) getMatchCache(dataType).getIfPresent(getCacheKey(dataType, key));
        } catch (Exception ex) {
            logger.error("获取缓存发生异常:{}", getCacheKey(dataType, key), ex);
        }
        return null;
    }

    public static void remove(CacheDataType dataType,String key) {
        try {
            getMatchCache(dataType).invalidate(getCacheKey(dataType, key));
        } catch (Exception ex) {
            logger.error("清除缓存发生异常:{}", getCacheKey(dataType, key), ex);
        }
    }

    private static String getCacheKey(CacheDataType dataType,String key) {
        return String.format("%s_%s", dataType, key);
    }

    private static Cache<String, Object> getMatchCache(CacheDataType dataType) {
        return _hotCache;
    }

    public static Collection<String> getKeys() {
        return _hotCache.asMap().keySet();
    }

    public static enum CacheDataType {
        SecurityStation,
        EnableFaceValidation
    }

    public static final String KEY_ENABLE_FACE_VALIDATION="FACE_VALIDATION_SETTING";
}
