package com.ssyf.plugs.cache.service.impl;

import com.ssyf.plugs.cache.service.CacheService;
import com.ssyf.plugs.cache.service.DataProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.util.Set;


/**
 * 二级缓存，整合本地缓存和redis缓存
 * @author huwei
 * @date 2023/9/21 14:46
 */
@Service
@ConditionalOnBean({RedisCacheService.class ,EhcacheCacheService.class})
public class SecondLevelCacheService implements CacheService {

    @Autowired
    private RedisCacheService redisCacheService;

    @Autowired
    private EhcacheCacheService ehcacheCacheService;

    @Override
    public <T> T put(long timeoutSecond, String key, T obj, String... prefix) {
        //更新一级缓存
        this.ehcacheCacheService.put(timeoutSecond, key, obj, prefix);
        //更新二级缓存
        this.redisCacheService.put(timeoutSecond, key, obj, prefix);
        return obj;
    }

    @Override
    public <T> T get(String key, String... prefix) {
       T t =  this.ehcacheCacheService.get(key, prefix);
       if(t != null){
           return t;
       }
       t = this.redisCacheService.get(key, prefix);
       if(t != null){
           this.ehcacheCacheService.put(key, t ,prefix);
       }
       return t;
    }

    @Override
    public <T> T getOrPutIfAbsent(long timeoutSecond, String key, DataProducer<? extends T> producer, String... prefix) {
        T t = get(key, prefix);
        if(t != null){
            return t;
        }
        t = producer.product();
        //都没有指定的缓存数据，生产数据缓存之后并返回
        return put(timeoutSecond ,key ,t,prefix);
    }

    @Override
    public Set<String> keys(String... prefix) {
        return this.ehcacheCacheService.keys(prefix);
    }

    @Override
    public boolean isExists(String key, String... prefix) {
        return this.ehcacheCacheService.isExists(key, prefix);
    }

    @Override
    public boolean remove(String key, String... prefix) {
        this.ehcacheCacheService.remove(key, prefix);
        this.redisCacheService.remove(key, prefix);
        return true;
    }

    @Override
    public boolean clearPrefix(String... prefix) {
        this.ehcacheCacheService.clearPrefix(prefix);
        this.redisCacheService.clearPrefix(prefix);
        return false;
    }

}
