package com.bcxin.tenant.open.domains.components;

import com.bcxin.tenant.open.infrastructures.components.JsonProvider;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.function.Supplier;

@Component
public class CacheProviderImpl implements CacheProvider{
    private final RedisTemplate redisTemplate;
    private final JsonProvider jsonProvider;

    public CacheProviderImpl(RedisTemplate redisTemplate, JsonProvider jsonProvider) {
        this.redisTemplate = redisTemplate;
        this.jsonProvider = jsonProvider;
    }

    @Override
    public <T> T get(String key, Supplier<T> supplier, Class<T> tClass) {
        try {
            T data = this.get(key,tClass);

            if (data == null) {
                data = supplier.get();
                if (data != null) {
                    this.redisTemplate.opsForValue().set(key, this.jsonProvider.getJson(data));
                }
            }

            return data;
        } catch (Exception ex) {
            return supplier.get();
        }
    }

    @Override
    public void delete(String key) {
        this.redisTemplate.delete(key);
    }

    @Override
    public <T> T get(String key, Class<T> tClass) {
        String content = (String) this.redisTemplate.opsForValue().get(key);
        T data = null;
        if (StringUtils.hasLength(content)) {
            data = this.jsonProvider.toObject(tClass, content);
        }

        return data;
    }
}
