package com.airlock.iam.factor.domain.model.fido;

import com.airlock.iam.common.api.domain.model.valueprovider.ValueProvider;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Optional;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import rocks.xmpp.precis.PrecisProfiles;

public final class FidoCredentialName {
   private static final ELogger LOG = ELoggerFactory.getLogger(FidoCredentialName.class);
   private static final int MAXIMAL_LENGTH = 100;
   public static final String DEFAULT_CREDENTIAL_NAME = "-";
   @NonNull
   private final String name;

   private FidoCredentialName(@NonNull String name) {
      if (name == null) {
         throw new NullPointerException("name is marked non-null but is null");
      }

      String normalizedName = null;

      try {
         normalizedName = StringUtils.truncate(PrecisProfiles.USERNAME_CASE_PRESERVED.enforce(name), 100);
      } catch (IllegalArgumentException e) {
         LOG.debug(
            String.format("The string '%s' is not a valid FIDO credential name. Replacing invalid value with '%s'. Cause: '%s'", name, "-", e.getCause())
         );
      } finally {
         this.name = Optional.ofNullable(normalizedName).orElse("-");
      }
   }

   public static FidoCredentialName credentialName(String name) {
      return new FidoCredentialName(name);
   }

   public static FidoCredentialName emptyCredentialName() {
      return credentialName("-");
   }

   public static FidoCredentialName credentialName(Optional<ValueProvider<String>> nameProvider) {
      return nameProvider.map(ValueProvider::getValue).filter(StringUtils::isNotBlank).map(FidoCredentialName::credentialName).orElse(emptyCredentialName());
   }

   @Override
   public String toString() {
      return this.getName();
   }

   @NonNull
   @SuppressFBWarnings(justification = "generated code")
   public String getName() {
      return this.name;
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public boolean equals(Object o) {
      if (o == this) {
         return true;
      } else if (!(o instanceof FidoCredentialName other)) {
         return false;
      } else {
         Object this$name = this.name;
         Object other$name = other.name;
         return this$name == null ? other$name == null : this$name.equals(other$name);
      }
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public int hashCode() {
      int PRIME = 59;
      int result = 1;
      Object $name = this.name;
      return result * 59 + ($name == null ? 43 : $name.hashCode());
   }
}
