package thyyxxk.webserver.service;


import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.function.Function;
import java.util.function.Supplier;

@Slf4j
@Component
public class RedisServer {

    public static String USER_INFO(String code) {
        return StrUtil.format("HIS_USERINFO-{}", code);
    }

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisServer(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setData(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @SuppressWarnings("unchecked")
    public <T> T getData(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            return null;
        }
        return (T) o;
    }

    @SuppressWarnings("unchecked")
    public <T> T getData(String key, Function<String, T> function) {
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            if (function == null) {
                throw new RuntimeException("function should not be null");
            }
            T data = function.apply(key);
            setData(key, data);
            return data;
        }
        return (T) o;
    }

    public <T> T getData(String key, Supplier<T> function) {
        return getData(key, (k) -> function.get());
    }

    public Boolean delData(String key) {
        return redisTemplate.delete(key);
    }

}
