package org.jfox.ejb;

import java.io.Serializable;
import java.net.InetAddress;

/**
 * ObjectId 用来保证 Container 中的 ejb object 的唯一性
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class ObjectId implements Serializable {

  /**
   * 用来辨别客户端和 Container 是否在同一个 JVM 中
   * 在部署第一个 EJB 的时候,该变量初始化,如果在客户端得到的 CONTAINTER_IDENTITY 和序列化过来的
   * identity 一致,则表明客户端和 Container 在同一个 JVM 中
   * 见 DelegateInvocactionHandler
   */
  private static String IPAddress = "127.0.0.1";
  static {
    try {
      IPAddress = InetAddress.getLocalHost().getHostAddress();
    }
    catch(Exception e){
//      e.printStackTrace();
    }
  };
  public final static String CONTAINER_IDENTITY = IPAddress + "-" + Long.toString(System.currentTimeMillis());
  private String identity = CONTAINER_IDENTITY;

  private String ipAddress;
  private String remoteInterf;
  private String homeInterf;
  private int hash;
  private boolean isHome;

  ObjectId(String ipAddress,String homeInterf,String remoteInterf, int hash, boolean isHome) {
    this.ipAddress = ipAddress;
    this.homeInterf = homeInterf;
    this.remoteInterf = remoteInterf;
    this.hash = hash;
    this.isHome = isHome;
  }

  public String toString() {
    StringBuffer sb = new StringBuffer();
    if(isHome){
      sb.append(homeInterf);
    }
    else {
      sb.append(remoteInterf);
    }
    sb.append("@").append(hash);
    return sb.toString();
  }

  /**
   *
   * @return 这个 ejb 的 name ,作为 ejb container 中的 key
   */
  public String getRemoteInterfaceName() {
    return remoteInterf;
  }

  public String getHomeInterfName() {
    return homeInterf;
  }

  public boolean isHome(){
    return isHome;
  }

  public String getIpAddress() {
    return ipAddress;
  }

  public int hashCode() {
    return hash;
  }

  /**
   *
   * @return 完整的 Object ID, name@hashCode
   */
  public String getStringObjectId() {
    return this.toString();
  }

  public boolean equals(Object obj) {
    if(!(obj instanceof ObjectId)) return false;
    return ((ObjectId)obj).getStringObjectId().equals(this.getStringObjectId());
  }

  public String getIdentity(){
    return identity;
  }
}