package cn.com.ty.lift.enterprise.config;

import cn.com.ty.lift.common.verify.Validation;
import cn.com.ty.lift.common.verify.Val;
import cn.com.ty.lift.common.verify.Validator;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Objects;

/**
 * the {@link MethodInterceptor} for verify parameter.
 *
 * @author wcz
 * @since 2020/3/15
 */
public class ValidateMethodInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        //check whether the method is present with validation annotation.
        Method method = invocation.getMethod();
        boolean annotationPresent = method.isAnnotationPresent(Validation.class);
        if(!annotationPresent){
            return invocation.proceed();
        }
        //check the list of parameters.
        Parameter[] parameters = method.getParameters();
        if(Objects.isNull(parameters) || parameters.length == 0){
            return invocation.proceed();
        }
        //if the parameter is present with Val. return the index.
        Object object = null;
        Object[] arguments = invocation.getArguments();
        for (int i = 0; i < parameters.length; i++) {
            if(parameters[i].isAnnotationPresent(Val.class)){
                object = arguments[i];
                break;
            }
        }
        if(Objects.isNull(object)){
            return invocation.proceed();
        }
        Validation validation = method.getDeclaredAnnotation(Validation.class);
        Validator.valid(object, validation.fields());
        return invocation.proceed();
    }
}
