package cn.wise.sc.cement.business.config;

import cn.wise.sc.cement.business.filter.SwaggerInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.MappedInterceptor;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

	//api接口包扫描路径
	public static final String SWAGGER_SCAN_BASE_PACKAGE = "cn.wise.sc.cement.business.controller";

	public static final String VERSION = "1.0.0";

	@Bean
	public Docket docket() {
		return new Docket(DocumentationType.SWAGGER_2).groupName("swagger接口文档")
				.apiInfo(new ApiInfoBuilder().title("swagger接口文档")
						.contact(new Contact("Wisenergy", "http://www.wisenergy.cn/", "service@wisenergy.cn"))
						.description("天津院项目")
						.version(VERSION).build())
				.select()
				.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
				.paths(PathSelectors.any()).build()
				.securitySchemes(newArrayList(apiKey()))
				.securityContexts(newArrayList(securityContext()))
				.enableUrlTemplating(false)
				;
	}

	private ApiKey apiKey() {
		return new ApiKey("BearerToken", "Authorization", "header");
	}

	private SecurityContext securityContext() {
		return SecurityContext.builder()
				.securityReferences(defaultAuth())
				.forPaths(PathSelectors.regex("/.*"))
				.build();
	}

	List<SecurityReference> defaultAuth() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		return newArrayList(new SecurityReference("BearerToken", authorizationScopes));
	}

	@Value("${swagger.basic.username}")
	private String username;
	@Value("${swagger.basic.password}")
	private String password;

	/* 必须在此处配置拦截器,要不然拦不到swagger的静态资源 */
	@Bean
	@ConditionalOnProperty(name = "swagger.basic.enable", havingValue = "true")
	public MappedInterceptor getMappedInterceptor() {
		return new MappedInterceptor(new String[]{"/swagger-ui.html", "/webjars/**"}, new SwaggerInterceptor(username, password));
	}
}