package gaf3.core.cache

import org.springframework.data.redis.core.RedisTemplate
import java.util.concurrent.TimeUnit

class RedisCacheService(private val template: RedisTemplate<String, String>?, val config: GafCacheConfigure) : CacheService {

    override fun getCache(key: String): String? {
        return template?.opsForValue()?.get(nsKey(key))
    }

    override fun setCache(key: String, value: String, expired: Long?) {
        val exp = expired ?: config.validitySec
        if (exp > 0) {
            template?.opsForValue()?.set(nsKey(key), value, exp, TimeUnit.SECONDS)
            //template.expire(nsKey(key), expire, TimeUnit.MILLISECONDS);
        } else {
            template?.opsForValue()?.set(nsKey(key), value)
        }
    }

    override fun delCache(key: String) {
        template?.delete(nsKey(key))
    }

    fun nsKey(key: String): String {
        return config.namespace?.let {
            "${it}:${key}"
        } ?: key
    }
}