package com.ssyf.plugs.cache.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ssyf.plugs.cache.CacheMessage;
import com.ssyf.plugs.cache.helper.CacheHelper;
import com.ssyf.plugs.cache.properties.CacheProperties;
import com.ssyf.plugs.cache.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

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

/**
 * redis缓存服务类
 * @author huwei
 * @date 2023/9/21 14:52
 */
@Slf4j
@Service
@ConditionalOnBean(RedisTemplate.class)
public class RedisCacheService implements CacheService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private CacheProperties cacheProperties;

    @Override
    public <T> T put(long timeoutSecond, String key, T obj, String... prefix) {
        if(obj != null){
            String realKey = wrapKey(key, prefix);
            Object realValue = CacheHelper.wrapValue(obj);
            this.redisTemplate.opsForValue().set(realKey ,realValue ,timeoutSecond , TimeUnit.SECONDS);
            log.debug("[cache]cache value,key={},value={}" ,realKey ,obj);
        }
        return obj;
    }

    @Override
    public <T> T get(String key, String... prefix) {
        String realKey = wrapKey(key, prefix);
        Object obj = this.redisTemplate.opsForValue().get(realKey);
        log.debug("[cache]get cache,key={},value={}" ,realKey ,obj);
        return CacheHelper.parseValue(obj);
    }

    @Override
    public Set<String> keys(String... prefix) {
        return this.redisTemplate.keys(parseAndGetPrefix(prefix) + "*");
    }

    @Override
    public boolean isExists(String key, String... prefix) {
        return this.redisTemplate.hasKey(wrapKey(key, prefix));
    }

    @Override
    public boolean remove(String key, String... prefix) {
        String realKey = wrapKey(key, prefix);
        this.redisTemplate.delete(realKey);
        log.debug("[cache]remove cache,key={}" ,realKey);
        //通知其他redis节点
        this.redisTemplate.convertAndSend(this.cacheProperties.getTopic(), new CacheMessage(parseAndGetPrefix(prefix) ,realKey , IdUtil.simpleUUID()));
        return true;
    }

    @Override
    public boolean clearPrefix(String... prefix) {
        this.keys(prefix).forEach(key->{
            this.redisTemplate.delete(key);
        });
        log.debug("[cache]clear cache,prefix={}" ,parseAndGetPrefix(prefix));
        return true;
    }
}
