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

import com.airlock.iam.application.parameters.domain.model.LoginappParameters;
import com.airlock.iam.application.resources.infrastructure.ApplicationResource;
import com.airlock.iam.application.resources.infrastructure.ResourceLocator;
import com.airlock.iam.application.webserver.infrastructure.deploy.util.inlined.LegacyCookieProcessor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;

public final class LoginappDeployer implements Deployer {
   private final LoginappParameters parameters;
   private final ResourceLocator resourceLocator;

   public LoginappDeployer(LoginappParameters parameters, ResourceLocator resourceLocator) {
      this.parameters = parameters;
      this.resourceLocator = resourceLocator;
   }

   @Override
   public Context deploy(Tomcat tomcat) {
      Context context = new IamWebAppModuleDeployer(this.parameters, this.resourceLocator).deploy(tomcat);
      ContextConfigurator.setDefaultValues(context, this.createLegacyCookieProcessor());
      List<Path> layoutDirs = this.getLayoutDirectories();
      ContextConfigurator.setContextFile(context, layoutDirs);
      ContextConfigurator.addLayoutDirectories(context, layoutDirs);
      this.parameters.uiCustomizations().ifPresent(customizations -> {
         if (Files.notExists(customizations)) {
            throw new IllegalStateException("Loginapp UI customizations file does not exist: " + customizations);
         }

         ContextConfigurator.addSpaCustomizationResource(context, customizations, "/ui");
      });
      this.parameters.uiResourceSetBasePath().ifPresent(uiResourceSetBasePath -> {
         if (Files.notExists(uiResourceSetBasePath)) {
            throw new IllegalStateException("Loginapp UI resource set base path does not exist: " + uiResourceSetBasePath);
         }

         if (!Files.isDirectory(uiResourceSetBasePath)) {
            throw new IllegalStateException("Loginapp UI resource set base path is not a directory: " + uiResourceSetBasePath);
         }

         ContextConfigurator.addSpaResourceSets(context, uiResourceSetBasePath, "/ui");
      });
      return context;
   }

   private List<Path> getLayoutDirectories() {
      Path defaultLayoutDir = this.resourceLocator.getPath(ApplicationResource.LOGINAPP_LAYOUT_DEFAULT);
      return Stream.concat(this.parameters.layoutDirectories().stream(), Stream.of(defaultLayoutDir)).collect(Collectors.toList());
   }

   private LegacyCookieProcessor createLegacyCookieProcessor() {
      LegacyCookieProcessor cookieProcessor = new LegacyCookieProcessor();
      cookieProcessor.setAllowEqualsInValue(this.parameters.allowEqualsInValue());
      cookieProcessor.setAllowHttpSepsInV0(this.parameters.allowHttpSepsInV0());
      return cookieProcessor;
   }
}
