package com.infoclinika.pdx.config;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static org.springframework.http.HttpStatus.NOT_FOUND;

/**
 * Spring configuration to serve single page application.
 */
@Configuration
public class SinglePageAppConfig implements WebMvcConfigurer {
    private static final ErrorPage NOT_FOUND_PAGE = new ErrorPage(NOT_FOUND, "/404");

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/ui/build/default/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        /*
          Forward all requests to 'index.html' except those that start with '/api'
         */
        registry.addViewController("/").setViewName("index.html");
        // No need to exclude `/api` for single directory level
        registry.addViewController("/{page:[\\w-]+}").setViewName("forward:/");
        // Exclude `/api` for multi directory level
        registry.addViewController("/{root:^(?!api|static).*$}/**/{page:[\\w-]+}").setViewName("forward:/");
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
        return container -> container.addErrorPages(NOT_FOUND_PAGE);
    }
}
