package com.boman.web.core.idempotency;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;

/**
 * @author shiqian
 * @date 2021年08月26日 18:41
 **/
@Aspect
@Component
public class IdempotencyAop {

    private static final Logger log = LoggerFactory.getLogger(IdempotencyAop.class);

    /**
     * 功能描述: 切点为 com.boman.web.core.idempotency.BomanIdempotency
     */
    @Pointcut(value = "@annotation(com.boman.web.core.idempotency.BomanIdempotency)")
    public void access() {}

    /**
     * 功能描述: doBefore
     *
     * @param joinPoint joinPoint
     */
    @Before("access()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = getRequest();
        MethodSignature methodSignature = getMethodSignature(joinPoint);
        Method method = methodSignature.getMethod();
        BomanIdempotency annotation = method.getAnnotation(BomanIdempotency.class);
        if (Objects.isNull(annotation)) {

            return;
        }

        String[] parameterNames = methodSignature.getParameterNames();
        Map<String, String[]> parameterMap = request.getParameterMap();



    }

    /**
     * 功能描述: 获取request
     *
     * @return javax.servlet.http.HttpServletRequest
     */
    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        return attributes.getRequest();
    }

    /**
     * 功能描述: 获取MethodSignature
     *
     * @param joinPoint joinPoint
     * @return org.aspectj.lang.reflect.MethodSignature
     */
    public MethodSignature getMethodSignature(JoinPoint joinPoint) {
        return ((MethodSignature) joinPoint.getSignature());
    }

    public void checkAnnotation(Method method){
        BomanIdempotency annotation = method.getAnnotation(BomanIdempotency.class);
        if (Objects.nonNull(annotation)) {

        }
    }

}
