package studycave.studycaverestservice.config;

import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.base.Predicates;
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.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    private ApiInfo metaData() {
        return new ApiInfoBuilder().title("StudyCave API").description("Spring Boot REST Api for StudyCave")
                .version("1.0.0").build();
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error.*"))) // exclude Basic Error Controller
                .build().apiInfo(metaData())
                .securitySchemes(Arrays.asList(apiKey()))
                .securityContexts(Arrays.asList(securityContext));
    }

    SecurityReference securityReference = SecurityReference.builder()
            .reference("apiKey")
            .scopes(new AuthorizationScope[0])
            .build();

    SecurityContext securityContext = SecurityContext.builder()
            .securityReferences(Arrays.asList(securityReference))
            .forPaths((Predicates.not(PathSelectors.regex("/login.*"))))
            .build();

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

