package com.codvision.webcore.config.encrypt;

import com.codvision.webcore.annotation.ApiSecret;
import org.springframework.core.MethodParameter;

import java.util.HashSet;
import java.util.Set;

/**
 * @author hxl
 */
public class ApiSecretSupports {
    private static final Set<String> IGNORES = new HashSet<>();

    static {
        IGNORES.add("com.anji.captcha.controller.CaptchaController");
        IGNORES.add("springfox.documentation.swagger.web.ApiResourceController");
        IGNORES.add("springfox.documentation.swagger2.web.Swagger2Controller");
        IGNORES.add("org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController");
    }

    public static boolean supports(MethodParameter parameter, ApiSecretProperties properties) {
        if (IGNORES.contains(parameter.getDeclaringClass().getName())) {
            return false;
        }

        return supports(parameter, properties.isGlobalEnabled());
    }

    private static boolean supports(MethodParameter parameter, boolean isGlobalEnabled) {
        ApiSecret cApiSecret = parameter.getContainingClass().getAnnotation(ApiSecret.class);
        if (cApiSecret == null) {
            ApiSecret apiSecret = parameter.getMethodAnnotation(ApiSecret.class);
            if (apiSecret == null) {
                return isGlobalEnabled;
            }

            return !apiSecret.ignore();
        }

        if (cApiSecret.ignore()) {
            return false;
        }

        ApiSecret apiSecret = parameter.getMethodAnnotation(ApiSecret.class);
        if (apiSecret == null) {
            return true;
        }

        return !apiSecret.ignore();
    }
}
