package net.northking.cctp.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.paths.AbstractPathProvider;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 * @author xiusong.xie
 * @since 2.4
 */
@Configuration
@EnableSwagger2
@RefreshScope
@ConditionalOnProperty(name = "nk.swagger2.enable", havingValue = "true")
public class SwaggerConfiguration
{
  private static final Logger logger = LoggerFactory.getLogger(SwaggerConfiguration.class);

  @Value("${nk.swagger2.basePackage:net.northking.gz}")
  private String basePackage;

  @Value("${nk.swagger2.title: XXXX Rest API}")
  private String title;

  @Value("${nk.swagger2.description: XXXX Rest API}")
  private String description;

  @Value("${nk.swagger2.version: 2.4}")
  private String version;

  /**
   * 配置swagger2
   *
   * @return 配置
   */
  @Bean
  public Docket createRestApi()
  {
    Docket docket = new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage(basePackage))
        .paths(PathSelectors.any())
        .build()
        .securitySchemes(securitySchemes())
        .securityContexts(securityContexts());
    docket.pathProvider(new AbstractPathProvider()
                        {
                          @Override
                          protected String applicationPath()
                          {
                            return "/";
                          }

                          @Override
                          protected String getDocumentationPath()
                          {
                            return "/";
                          }
                        }
    );
    logger.info("注册公共组件提示：统一配置 在线接口文档（Swagger2 UI） 已完成。");
    logger.info("在线接口文档地址：/doc.html 或者 /swagger-ui.html");
    return docket;
  }

  private List<ApiKey> securitySchemes()
  {
    List<ApiKey> apiKeys = new ArrayList<>();
    apiKeys.add(new ApiKey(HttpHeaders.AUTHORIZATION, HttpHeaders.AUTHORIZATION, "header"));
    return apiKeys;
  }

  private List<SecurityContext> securityContexts()
  {
    AuthorizationScope scope = new AuthorizationScope("global", "access Everything");
    AuthorizationScope[] scopes = new AuthorizationScope[]{scope};
    List<SecurityReference> references = new ArrayList<>();
    references.add(new SecurityReference(HttpHeaders.AUTHORIZATION, scopes));

    List<SecurityContext> contexts = new ArrayList<>();
    contexts.add(SecurityContext.builder().securityReferences(references).build());
    return contexts;
  }

  private ApiInfo apiInfo()
  {
    return new ApiInfoBuilder()
        .title(title)
        .description(description)
        .version(version)
        .build();
  }
}
