package com.bcxin.Infrastructures.components;

import com.bcxin.Infrastructures.components.models.CacheItemAbstract;
import com.bcxin.Infrastructures.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

public interface CacheProvider {
    <T extends CacheItemAbstract> T get(String key, Supplier<T> supplier);

    <T extends CacheItemAbstract> void put(String key, T data);

    void delete(String key);

    @Component
    @Slf4j
    public static class DefaultCacheProviderImpl implements CacheProvider {
        private static Map<String, CacheItemAbstract> _localCachedContainer = new ConcurrentHashMap<>();

        @Override
        public <T extends CacheItemAbstract> T get(String key, Supplier<T> supplier) {
            T data = null;
            try {
                data = (T) _localCachedContainer.get(key);
            } catch (Exception ex) {
                log.error("获取缓存({})数据发送异常:{}", key, ExceptionUtil.getStackMessage(ex));
            } finally {
                if (data == null || data.isExpired()) {
                    data = supplier.get();
                    _localCachedContainer.put(key, data);
                }
            }

            return data;
        }

        @Override
        public <T extends CacheItemAbstract> void put(String key, T data) {
            _localCachedContainer.put(key, data);
        }

        @Override
        public void delete(String key) {
            _localCachedContainer.remove(key);
        }
    }
}