package com.pwt.common.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author linyun
 * @version V1.0
 * @Title: CacheMap
 * @Description: 站控初始数据缓存
 * @date 2022/11/23
 **/
public class CacheMap {

    public static Map<String, Object> CACHE_MAP = new ConcurrentHashMap<>();

    private static final String CACHE_KEY = "cache_key";

    private static final long HOLD_TIME = 1000;

    public static void put(String cacheName, Object obj)
    {
        CACHE_MAP.put(cacheName, obj);
    }

    public static void put(String cacheName, Object obj, long second)
    {
        CACHE_MAP.put(cacheName, obj);
        CACHE_MAP.put(cacheName + CACHE_KEY, System.currentTimeMillis() + (second * HOLD_TIME));//缓存失效时间
    }

    /**
     * 获取系统初始化value
     */
    public static Object get(String cacheName)
    {
        return CACHE_MAP.get(cacheName);
    }

    /**
     * 获取缓存value
     */
    public static Object getCache(String cacheName)
    {
        if (checkCacheName(cacheName))
        {
            return CACHE_MAP.get(cacheName);
        }
        return null;
    }

    public static void remove(String cacheName)
    {
        CACHE_MAP.remove(cacheName);
        CACHE_MAP.remove(cacheName + CACHE_KEY);
    }

    public static boolean hasKey(String CACHE_KEY)
    {
        return CACHE_MAP.containsKey(CACHE_KEY);
    }

    private static boolean checkCacheName(String cacheName)
    {
        Long cacheTime = (Long) CACHE_MAP.get(cacheName + CACHE_KEY);
        if (cacheTime == null || cacheTime == 0L)
        {
            return false;
        }
        if (cacheTime < System.currentTimeMillis())
        {
            remove(cacheName);
            return false;
        }
        return true;
    }
}
