package com.sonic.pigeon.config;


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 springfox.documentation.RequestHandler;
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
@EnableSwagger2
public class SwaggerConfig {

    private static final String SPLIT = ",";

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

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

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


    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;
        };
    }

    @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>();
        ticketPar.name("_tk_")
                //name表示名称，description表示描述
                .description("token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .defaultValue("")
                .build();//required表示是否必填，defaultvalue表示默认值

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


        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(swaggerEnabled)
                .select()
                .apis(basePackage(basePackageValue))
                .paths(PathSelectors.any())
                .build()
                //************把消息头添加
                .globalOperationParameters(pars);
    }

    /**
     * TODO: 更改文案配置
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("sonic-bear")
                .description("sonic-bear API")
                .version("1.0")
                .contact(new Contact("sonic-bear", "", "admin.sonic-bear.com"))
                .build();
    }

}
