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

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Duration;
import java.util.jar.JarFile;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.webresources.WarResourceSet;

public final class SpaCustomizationZipResourceSet extends WarResourceSet {
   private SpaCustomizationZipFileAttributes nowActiveAttributes;
   private final SpaCacheReloadManager spaCacheReloadManager;

   public SpaCustomizationZipResourceSet(WebResourceRoot resourceRoot, String mount, Path zip) throws IllegalArgumentException {
      super(resourceRoot, mount, zip.toString());
      this.setStaticOnly(true);
      this.nowActiveAttributes = SpaCustomizationZipFileAttributes.fromFile(zip.toFile());
      this.spaCacheReloadManager = new SpaCacheReloadManager();
   }

   SpaCustomizationZipResourceSet(WebResourceRoot resourceRoot, String mount, Path zip, Duration cacheReloadDelay) throws IllegalArgumentException {
      super(resourceRoot, mount, zip.toString());
      this.setStaticOnly(true);
      this.nowActiveAttributes = SpaCustomizationZipFileAttributes.fromFile(zip.toFile());
      this.spaCacheReloadManager = new SpaCacheReloadManager(cacheReloadDelay);
   }

   protected JarFile openJarFile() throws IOException {
      SpaCustomizationZipFileAttributes possibleNewerAttributes = SpaCustomizationZipFileAttributes.fromFile(new File(this.getBase()));
      boolean hasNewerAttributes = !this.nowActiveAttributes.equals(possibleNewerAttributes);
      if (hasNewerAttributes) {
         this.spaCacheReloadManager.setCacheReloadAttributeWithDelay(this.getRoot().getContext().getServletContext());
      }

      this.nowActiveAttributes = possibleNewerAttributes;
      return super.openJarFile();
   }
}
