package com.tanpu.community.cache;

import com.alibaba.fastjson.JSON;
import com.tanpu.common.redis.RedisHelper;
import com.tanpu.common.redis.RedisKeyHelper;
import com.tanpu.community.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Aspect
@Component
public class RedisCacheEvictAspect {

    private static RedisKeyHelper keyHelper = new RedisKeyHelper("community2_cache:");

    @Around(value = "@annotation(com.tanpu.community.cache.CacheEvict)")
    public Object methodAround(ProceedingJoinPoint jp) throws Throwable {

        MethodSignature ms = (MethodSignature) jp.getSignature();
        CacheEvict anno = ms.getMethod().getAnnotation(CacheEvict.class);
        String prefix = anno.prefix();

        RedisHelper redisHelper = SpringUtils.getBean(RedisHelper.class);
        String key = keyHelper.buildKeyCustom(":", prefix, StringUtils.joinWith(":", jp.getArgs()));
        redisHelper.delete(key);

        try {
            Object ret = jp.proceed();
            return ret;
        } catch (Throwable t) {
            // todo wrap this throwable
            throw new RuntimeException(t);
        }
    }
}