package com.bcxin.Infrastructures.components;

import com.bcxin.Infrastructures.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Set;
import java.util.function.Supplier;

@Component
public class RedisCacheProviderImpl implements CacheV2Provider {
    private static final Logger logger = LoggerFactory.getLogger(RedisCacheProviderImpl.class);

    private final RedisUtil redisUtil;

    public RedisCacheProviderImpl(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public <T> T get(String key, Supplier<T> supplier) {
        return get(key, supplier, 120);
    }

    @Override
    public <T> T get(String key, Supplier<T> supplier, int inSeconds) {
        T data = null;
        try {
            data = (T) redisUtil.get(key);
        } catch (Exception ex) {
            logger.error("Redis({}).get调用出错: 异常:{}",key,ex);
        } finally {
            if (data == null || (data instanceof Collection && CollectionUtils.isEmpty((Collection<?>) data))) {
                data = supplier.get();

                put(key, data, inSeconds);
            }
        }

        return data;
    }

    @Override
    public <T> void put(String key, T data, int inSeconds) {
        try
        {
            redisUtil.set(key, data, inSeconds);
        }
        catch (Exception ex)
        {
            logger.error("Redis({}).put调用出错: 异常:{}",key,ex);
        }
    }

    @Override
    public void del(String... keys) {
        try {
            redisUtil.del(keys);
        } catch (Exception ex) {
            logger.error("Redis({}).del调用出错: 异常:{}", keys, ex);
        }
    }

    /**
     * 模糊删除
     * @param key
     */
    @Override
    public void delFuzzy(String key) {
        try {
            redisUtil.deleteByPrex(key);
        } catch (Exception ex) {
            logger.error("Redis({}).delFuzzy调用出错: 异常:{}", key, ex);
        }
    }
}
