import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.util.IntrospectorCleanupListener;

/**
 * This initializer creates root context and registers dispatcher servlet
 * Spring scans for initializers automatically
 */
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  private static final Logger LOGGER = LoggerFactory.getLogger(WebAppInitializer.class);

  public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    servletContext.addListener(new IntrospectorCleanupListener());
  }

  protected String[] getServletMappings() {
    return new String[]{"/"};
  }

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[]{AppConfig.class};
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class[0];
  }

  @Override
  protected void customizeRegistration(ServletRegistration.Dynamic registration) {

    // read from env or assign default values
    int maxFileSize = parseOrDefault("ERVU_FILE_UPLOAD_MAX_FILE_SIZE", 5242880);
    int maxRequestSize = parseOrDefault("ERVU_FILE_UPLOAD_MAX_REQUEST_SIZE", 6291456);
    int fileSizeThreshold = parseOrDefault("ERVU_FILE_UPLOAD_FILE_SIZE_THRESHOLD", 0);

    MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
        "/tmp",
        maxFileSize,
        maxRequestSize,
        fileSizeThreshold);
    registration.setMultipartConfig(multipartConfigElement);

    LOGGER.info("Max file upload size is set to: " + multipartConfigElement.getMaxFileSize());
    LOGGER.info("Max file upload request size is set to: " + multipartConfigElement.getMaxRequestSize());
    LOGGER.info("File size threshold is set to: " + multipartConfigElement.getFileSizeThreshold());

  }

  private int parseOrDefault(String envVar, int defaultVal) {
    String envVarValue = System.getenv(envVar);
    if (envVar == null) {
      LOGGER.info("Environment variable {} is null, using default value: {}", envVar, defaultVal);
      return defaultVal;
    }
    try {
      return Integer.parseInt(envVarValue);
    } catch (NumberFormatException e) {
      LOGGER.info("Environment variable {} is not an integer, using default value: {}", envVar, defaultVal);
      return defaultVal;
    }
  }
}
