package com.njzscloud.common.cache;

import com.njzscloud.common.redis.util.Redis;
import io.lettuce.core.SetArgs;

import java.util.function.Supplier;

@SuppressWarnings("unchecked")
public class SecondCache implements Cache {

    private final long timeout;

    public SecondCache(long timeout) {
        this.timeout = timeout;
    }

    public <T> T get(String key) {
        return Redis.get(key);
    }

    @Override
    public <T> T get(String key, Supplier<T> supplier) {
        Object o = Redis.get(key);
        if (o != null) return (T) o;
        o = supplier.get();
        if (o != null) Redis.set(key, o);
        return (T) o;
    }

    @Override
    public <T> T get(String key, long timeout, Supplier<T> supplier) {
        Object o = Redis.get(key);
        if (o != null) return (T) o;
        o = supplier.get();
        if (o != null) Redis.set(key, o, new SetArgs().ex(timeout));
        return (T) o;
    }

    public void put(String key, Object value, long timeout) {
        Redis.set(key, value, new SetArgs().ex(timeout));
    }

    public void put(String key, Object value) {
        if (timeout > 0) Redis.set(key, value, new SetArgs().ex(timeout));
        else Redis.set(key, value);
    }

    public void remove(String key) {
        Redis.del(key);
    }
}
