package cn.reghao.tnb.content.app.util.redis.ds;

import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author reghao
 * @date 2021-03-07 17:44:23
 */
@Component
public class RedisOps {
    private final RedisOperations<String, String> redisOps;

    public RedisOps(RedisTemplate<String, String> redisTemplate) {
        this.redisOps = redisTemplate;
    }

    public Long eval(String lua, String[] keys, Object... values) {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(lua, Long.class);
        return redisOps.execute(redisScript, Arrays.asList(keys), values);
    }

    public boolean expire(String key, long timeout) {
        Boolean ret = redisOps.expire(key, timeout, TimeUnit.SECONDS);
        return ret != null && ret;
    }

    public long ttl(String key) {
        Long ttl = redisOps.getExpire(key);
        return ttl != null ? ttl : 0;
    }

    public boolean exists(String key) {
        Boolean ret = redisOps.hasKey(key);
        return ret != null && ret;
    }

    public Set<String> keys(String pattern) {
        return redisOps.keys(pattern);
    }

    public void del(String... key) {
        Long ret = redisOps.delete(List.of(key));
    }
}
