package com.face.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class SpelUtils {

    public static EvaluationContext buildContext(JoinPoint joinPoint) {
        int i = 0;
        DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
        String[] params = discoverer.getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
        EvaluationContext context = new StandardEvaluationContext();
        for (Object object : joinPoint.getArgs()) {
            context.setVariable("p".concat(String.valueOf(i)), object);
            if (params != null && params.length > 0) {
                context.setVariable(params[i], object);
            }
            i++;
        }
        return context;
    }

    public static Object getValue(EvaluationContext context, String expr) {
        ExpressionParser parser = new SpelExpressionParser();
        Object obj = parser.parseExpression(expr).getValue(context);
        return obj;
    }
}
