package org.jfox.ejb;

import java.net.InetAddress;
import java.util.Random;

/**
 * 生成唯一的 ObjectID
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class OIDGenerator {
  private String ipAddress;
  private String homeInterf;
  private String remoteInterf;
  private int homeHash = 0;

  private static Random random;
  static {
    try {
      random = new Random((long)(Math.random()*1E8));
    }
    catch(Exception e){

    }
  };


  private OIDGenerator(String ipAddress, String homeIntef, String remoteInterf) {
    this.ipAddress = ipAddress;
    this.homeInterf = homeIntef;
    this.remoteInterf = remoteInterf;
    this.homeHash = random.nextInt();
  }

  /**
   *
   * @param homeInterf Bean 的类名
   * @return
   */
  public static OIDGenerator newInstance(String ipAddress, String homeInterf,String remoteInterf){
    return new OIDGenerator(ipAddress,homeInterf,remoteInterf);
  }

  public ObjectId getHomeObjectId(){
    return new ObjectId(ipAddress,homeInterf,remoteInterf,homeHash,true);
  }

  public ObjectId nextBeanObjectId(){
    return new ObjectId(ipAddress,homeInterf,remoteInterf,random.nextInt(),false);
  }

  public static void main(String[] args) throws Exception {
    OIDGenerator oig = OIDGenerator.newInstance(InetAddress.getLocalHost().getHostAddress(),"org.jfox.TestHome","org.jfox.Test");
    System.out.println(oig.getHomeObjectId());
    System.out.println(oig.nextBeanObjectId());
    oig = OIDGenerator.newInstance(InetAddress.getLocalHost().getHostAddress(),"org.jfox.TestHome","org.jfox.Test");
    System.out.println(oig.getHomeObjectId());
    System.out.println(oig.nextBeanObjectId());

  }
}