package com.airlock.iam.application.webserver.infrastructure.deploy;

import jakarta.servlet.ServletContext;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public final class SpaCacheReloadManager {
   static final String SPA_CACHE_BUSTER_RELOAD = "SPA_CACHE_BUSTER_RELOAD";
   static final String SPA_CUSTOM_STYLES_RELOAD = "SPA_CUSTOM_STYLES_RELOAD";
   static final String SPA_CUSTOM_TITLE_RELOAD = "SPA_CUSTOM_TITLE_RELOAD";
   static final String SPA_I18N_CACHE_RELOAD = "SPA_I18N_CACHE_RELOAD";
   static final Duration DEFAULT_CACHE_RELOAD_DELAY = Duration.ofSeconds(10L);
   private final Duration cacheReloadDelay;
   private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

   public SpaCacheReloadManager() {
      this.cacheReloadDelay = DEFAULT_CACHE_RELOAD_DELAY;
   }

   public SpaCacheReloadManager(Duration cacheReloadDelay) {
      this.cacheReloadDelay = cacheReloadDelay;
   }

   public void setCacheReloadAttributeWithDelay(ServletContext servletContext) {
      this.executorService.schedule(() -> setCacheReloadAttribute(servletContext), this.cacheReloadDelay.toMillis(), TimeUnit.MILLISECONDS);
   }

   private static void setCacheReloadAttribute(ServletContext servletContext) {
      servletContext.setAttribute("SPA_CACHE_BUSTER_RELOAD", true);
      servletContext.setAttribute("SPA_CUSTOM_STYLES_RELOAD", true);
      servletContext.setAttribute("SPA_CUSTOM_TITLE_RELOAD", true);
      servletContext.setAttribute("SPA_I18N_CACHE_RELOAD", true);
   }
}
