package talk;

import java.net.*;
import java.util.StringTokenizer;

/** Class to store a username/hostname/tty tuple for a callee or
    caller.  Includes routines to parse addresses in the format used
    by unix talk.
*/
public class TalkAddress {
  /** username part of the address */
  public String userName = "";
  /** hostname part of the address */
  public String hostName = "";
  /** tty part of the address */
  public String tty = "";

  /** Default constructor.  Initializes all fields to "" */
  public TalkAddress() {}
  
  /** Initializes the fields of this from the address passed to it.
      @exception BadAddressException if format of address is wrong
      @see TalkAddress#fromString
  */
  public TalkAddress(String address) throws BadAddressException {
    fromString(address);
  }

  /** Returns the address stored in this in "username@hostname tty"
      format. */
  public String getAddressStr() {
    String ret = userName;
    if (hostName.length() > 0)
      ret = ret + "@" + hostName;
    if (tty.length() > 0)
      ret = ret + " " + tty;
    return ret;
  }

  /** Returns a printable representation of this address */
  public String toString() {
    return "TalkAddress@" + Integer.toHexString(hashCode()) + ": "
      + getAddressStr();
  }

  /**
     Parse a talk address, which must be in the format
     username[@hostname] [tty] */
  public void fromString(String address) throws BadAddressException {
    String rx = "\\s*([^\\s@]+)(@(\\S+))?(\\s+(\\S+))?\\s*";
    java.util.regex.Matcher matcher;
    try {
      matcher = java.util.regex.Pattern.compile(rx).matcher(address);
    } catch (java.util.regex.PatternSyntaxException e) {
      throw new RuntimeException("Bad Pattern: " + e);
    }
    if (matcher.matches()) {
      userName = matcher.group(1);
      hostName = matcher.group(3);
      tty = matcher.group(5);
      if (hostName == null) {
	try {
	  hostName = InetAddress.getLocalHost().getHostName();
	} catch (UnknownHostException e) {
	  hostName = "localhost";
	}
      }
      if (tty == null)
	tty = "";
    } else {
      throw new BadAddressException();
    }
  }  
}

