package com.ssyf.plugs.cache.cache;

import cn.hutool.core.util.ObjectUtil;
import com.ssyf.plugs.cache.helper.CacheHelper;
import com.ssyf.plugs.cache.properties.CacheProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;


/**
 * eh缓存
 * @author huwei
 * @date 2022/11/29 13:34
 */
@Slf4j
public class EhcacheCache extends AbstractCache {

    private EhCacheCacheManager ehCacheCacheManager;

    public EhcacheCache(String name, CacheProperties cacheProperties, EhCacheCacheManager ehCacheCacheManager) {
        super(name, cacheProperties);
        this.ehCacheCacheManager = ehCacheCacheManager;
    }

    /**
     * 执行底层查询操作
     *
     * @param key
     * @return
     */
    @Override
    protected Object lookup(Object key) {
        Cache cache = CacheHelper.getOrCreateCache(this.getName(), this.ehCacheCacheManager);
        Object value = cache.get(key);
        log.debug("从ehcache中获取数据：{}", value);
        return CacheHelper.parseValue(value);
    }


    @Override
    public void put(Object key, Object value) {
        if (!super.isAllowNullValues() && ObjectUtil.isEmpty(value)) {
            this.evict(key);
            return;
        }

        Cache cache = CacheHelper.getOrCreateCache(this.getName(), this.ehCacheCacheManager);
        cache.put(key, CacheHelper.wrapValue(value));
    }


    @Override
    public void evict(Object key) {
        Cache cache = CacheHelper.getOrCreateCache(this.getName(), this.ehCacheCacheManager);
        cache.evict(key);
    }

    @Override
    public void clear() {
        Cache cache = CacheHelper.getOrCreateCache(this.getName(), this.ehCacheCacheManager);
        cache.clear();
    }

    /**
     * 清除多级缓存值
     *
     * @param key
     */
    @Override
    public void clearLocal(Object key) {
        //删除一级缓存
        Cache cache = CacheHelper.getOrCreateCache(this.getName(), this.ehCacheCacheManager);
        if (key == null) {
            cache.clear();
        } else {
            cache.evict(key);
        }
    }

}