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

import com.airlock.iam.base.misc.log.LogUtil;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import rocks.xmpp.precis.PrecisProfiles;

public abstract class FidoDisplayName {
   private static final ELogger LOG = ELoggerFactory.getLogger(FidoDisplayName.class);
   @NonNull
   private final String name;

   protected FidoDisplayName(@NonNull String name, int maximalLength) throws IllegalArgumentException {
      if (name == null) {
         throw new NullPointerException("name is marked non-null but is null");
      }

      this.name = sanitize(name, maximalLength);
   }

   static String sanitize(@NonNull String name, int maximalLength) {
      if (name == null) {
         throw new NullPointerException("name is marked non-null but is null");
      } else if (name.length() > maximalLength) {
         LOG.debug(
            String.format(
               "Display name starting with '%s' is too long. Expected in total at most '%d' characters but got '%d'",
               LogUtil.logSafeString(StringUtils.truncate(name, maximalLength / 2)),
               maximalLength,
               name.length()
            )
         );
         throw new IllegalArgumentException(
            String.format("Display name is too long. Expected in total at most '%d' characters but got '%d'", maximalLength, name.length())
         );
      } else {
         return PrecisProfiles.NICKNAME.enforce(name);
      }
   }

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

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public boolean equals(Object o) {
      if (o == this) {
         return true;
      } else if (!(o instanceof FidoDisplayName other)) {
         return false;
      } else {
         if (!other.canEqual(this)) {
            return false;
         }

         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")
   protected boolean canEqual(Object other) {
      return other instanceof FidoDisplayName;
   }

   @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());
   }

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