package com.sonic.lion.config;


import com.sonic.common.auth.domains.Session;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * swagger配置
 * @author code
 */
@Slf4j
@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Value("${swagger.enabled}")
	private Boolean swaggerEnabled = false;

	@Value("${swagger.base.package}")
	private String basePackageValue;

	private static final String SPLIT = ",";

	private final String DEFAULT_BASE_PACKAGE = "com.sonic.web.controller";

//	@Bean
//	public Docket createRestApi() {
//		basePackageValue = null == basePackageValue || ("").equals(basePackageValue) ? DEFAULT_BASE_PACKAGE : basePackageValue;
//		log.info("===> swagger base package : ", basePackageValue);
//		return new Docket(DocumentationType.SWAGGER_2)
//			 .apiInfo(apiInfo())
//			 .enable(swaggerEnabled)
//			 .select()
//			 .apis(basePackage(basePackageValue))
//			 .paths(PathSelectors.any())
//			 .build();
//	 }

	@Bean
	public Docket createRestApi() {
		basePackageValue = null == basePackageValue || ("").equals(basePackageValue) ? DEFAULT_BASE_PACKAGE : basePackageValue;
		log.info("===> swagger base package : ", basePackageValue);

		//在配置好的配置类中增加此段代码即可
		ParameterBuilder ticketPar = new ParameterBuilder();
		List<Parameter> pars = new ArrayList<Parameter>();

		Parameter p1 = ticketPar.name("_tk_")
				.description("token")//name表示名称，description表示描述
				.modelRef(new ModelRef("string"))
				.parameterType("header")
				.required(false)
				.defaultValue("")
				.build();//required表示是否必填，defaultvalue表示默认值

		Parameter p2 = ticketPar.name("x-id")
				.description("x-id")//name表示名称，description表示描述
				.modelRef(new ModelRef("string"))
				.parameterType("header")
				.required(false)
				.defaultValue("")
				.build();//required表示是否必填，defaultvalue表示默认值

		pars.add(p1);//添加完此处一定要把下边的带***的也加上否则不生效
		pars.add(p2);//添加完此处一定要把下边的带***的也加上否则不生效

		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.enable(swaggerEnabled)
				.select()
				.apis(basePackage(basePackageValue))
				.paths(PathSelectors.any())
				.build()
				.ignoredParameterTypes(ApiIgnore.class, Session.class)
				.globalOperationParameters(pars);//************把消息头添加
	}
	
	private ApiInfo apiInfo(){
		return new ApiInfoBuilder()
                .title("sonic-lion")
                .description("sonic lion API")
                .version("1.0")
                .contact(new Contact("sonic","","admin.sonic"))
                .build();
	}

	public static Predicate<RequestHandler> basePackage(final String basePackage) {
		return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
	}

	private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
		return Optional.fromNullable(input.declaringClass());
	}

	private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
		return input -> {
			// 循环判断匹配
			for (String strPackage : basePackage.split(SPLIT)) {
				boolean isMatch = input.getPackage().getName().startsWith(strPackage);
				if (isMatch) {
					return true;
				}
			}
			return false;
		};
	}

}
