package com.gonghang.h5clientapp.config;

import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * swagger文档配置
 *
 * 访问地址：http://localhost:8089/swagger-ui.html
 * 优化后地址：http://localhost:8089/doc.html
 *
 * 参照：https://www.jianshu.com/p/7e543f0f0bd8
 *
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

	@Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(basePackage("com.gonghang.h5clientapp.web"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("掌上运维")
                .description("掌上运维-doc")
                .termsOfServiceUrl("http://localhost:8089/doc.html")
                .version("1.0")
                .build();
    }

    // 定义分隔符
    private static final String splitor = ";";

    private static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String everyPackage : basePackage.split(splitor)) {
                boolean isMatch = declaringClass(input).getPackage().getName().startsWith(everyPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Class<?> declaringClass(RequestHandler input) {
        return input.getHandlerMethod().getMethod().getDeclaringClass();
    }

}
