package com.elab.spring.intercept.annotation;

import com.elab.redis.utils.CacheParseUtil;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 特定注解拦截器
 *
 * @author ： liukx
 * @time ： 2020/7/9 - 20:02
 */
public class AnnotationAttributeSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {

    /**
     * 需要被拦截代理的注解列表
     */
    private Set<Class<? extends Annotation>> annotationsOperation = new LinkedHashSet<>(8);

    public void addAnnotations(Class<? extends Annotation> annotation) {
        annotationsOperation.add(annotation);
    }

    /**
     * 符合该注解的通通被代理起来
     *
     * @param method
     * @param targetClass
     * @return
     */
    @Override
    public boolean matches(Method method, Class<?> targetClass) {
        if (CacheParseUtil.isContainAnnotations(annotationsOperation, method)) {
            return true;
        }
        return false;
    }

    /**
     * 遍历该方法是否包含特定的注解
     *
     * @param annotations
     * @param element
     * @return
     */
    public boolean isContainAnnotations(Set<Class<? extends Annotation>> annotations, AnnotatedElement element) {
        boolean isContain = false;
        for (Class<? extends Annotation> annotation : annotations) {
            if (AnnotatedElementUtils.hasAnnotation(element, annotation)) {
                isContain = true;
                break;
            }
        }
        return isContain;
    }
}
