package org.jivesoftware.smack.util.dns;

import org.jivesoftware.smack.util.Objects;

public class HostAddress {
   private final String fqdn;
   private final int port;
   private Exception exception;

   public HostAddress(String fqdn) {
      this(fqdn, 5222);
   }

   public HostAddress(String fqdn, int port) {
      Objects.requireNonNull(fqdn, "FQDN is null");
      if (port >= 0 && port <= 65535) {
         if (fqdn.charAt(fqdn.length() - 1) == '.') {
            this.fqdn = fqdn.substring(0, fqdn.length() - 1);
         } else {
            this.fqdn = fqdn;
         }

         this.port = port;
      } else {
         throw new IllegalArgumentException("Port must be a 16-bit unsiged integer (i.e. between 0-65535. Port was: " + port);
      }
   }

   public String getFQDN() {
      return this.fqdn;
   }

   public int getPort() {
      return this.port;
   }

   public void setException(Exception e) {
      this.exception = e;
   }

   public Exception getException() {
      return this.exception;
   }

   public String toString() {
      return this.fqdn + ":" + this.port;
   }

   public boolean equals(Object o) {
      if (this == o) {
         return true;
      } else if (!(o instanceof HostAddress)) {
         return false;
      } else {
         HostAddress address = (HostAddress)o;
         if (!this.fqdn.equals(address.fqdn)) {
            return false;
         } else {
            return this.port == address.port;
         }
      }
   }

   public int hashCode() {
      int result = 1;
      int result = 37 * result + this.fqdn.hashCode();
      return result * 37 + this.port;
   }

   public String getErrorMessage() {
      return this.exception == null ? "No error logged" : "'" + this.toString() + "' failed because " + this.exception.toString();
   }
}
