package com.qmth.exam.reserve.cache;

import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisClient {

    private static final Logger log = LoggerFactory.getLogger(RedisClient.class);

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

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

    public void set(String key, Object value, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    public <T> T get(String key, Class<T> clazz) {
        return (T) redisTemplate.opsForValue().get(key);
    }

    public <T> T get(String key, Class<T> clazz, long timeout, TimeUnit timeUnit) {
        T object = (T) redisTemplate.opsForValue().get(key);
        expire(key, timeout, timeUnit);
        return object;
    }

    public <T> Map<String, T> getEntriesForHash(String key, Class<T> clazz) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);

        Map<String, T> result = new HashMap<>();
        if (entries.isEmpty()) {
            return result;
        }

        for (Map.Entry<Object, Object> entry : entries.entrySet()) {
            result.put((String) entry.getKey(), (T) entry.getValue());
        }

        return result;
    }

    public <T> T getForHash(String key, String hashKey, Class<T> clazz) {
        return (T) redisTemplate.opsForHash().get(key, hashKey);
    }

    public void setForHash(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    public void deleteForHash(String key, String hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    public void expire(String key, long timeout, TimeUnit timeUnit) {
        redisTemplate.expire(key, timeout, timeUnit);
    }

    public void delete(String key) {
        redisTemplate.expire(key, 0, TimeUnit.SECONDS);
    }

    public boolean exist(String key) {
        return redisTemplate.hasKey(key);
    }

    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public RedissonClient getRedissonClient() {
        return redissonClient;
    }

}
