package com.ejie.y42b.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Date;

import com.ejie.y42b.constantes.Y42bAgendaConstantes;

/**
 * 
 *  
 *
 */
public class Y42bUIDGenerator {

	private SecureRandom sRandom = null;
	private MessageDigest md = null;
	private static final Object monitor = new Object();
	private static Y42bUIDGenerator instance;

	/**
	 * 
	 * @return instance
	 */
	public static Y42bUIDGenerator getInstance() {
		synchronized (Y42bUIDGenerator.monitor) {
			if (Y42bUIDGenerator.instance == null) {
			    Y42bUIDGenerator.instance = new Y42bUIDGenerator();
			}
			return Y42bUIDGenerator.instance;
		}
	}
	
	/**
	 * 
	 */
	private Y42bUIDGenerator() {
		this.sRandom = new SecureRandom();
		this.sRandom.nextLong();
		try {
			this.md = MessageDigest.getInstance("SHA");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @return generateid
	 */
	public String generateId() {
		long timeStampLong = new Date().getTime();
		int objectHashCode = System.identityHashCode(this);
		long secureInt = this.sRandom.nextLong();

		String result = Long.toHexString(timeStampLong)
				+ Integer.toHexString(objectHashCode)
				+ Long.toHexString(secureInt);

		byte[] resultSha = this.md.digest(result.getBytes());
		StringBuffer strBuff = new StringBuffer();

		for (int i = 0; i < resultSha.length; ++i) {
			strBuff.append(this.toHexString(resultSha[i]));
		}
		return strBuff.toString();
	}

	/**
	 * 
	 * @param b b
	 * @return String
	 */
	private String toHexString(byte b) {
		int value = (b & Y42bAgendaConstantes.NUM_0x7F) + ((b < Y42bAgendaConstantes.NUM_0) ? Y42bAgendaConstantes.NUM_128 : Y42bAgendaConstantes.NUM_0);
		StringBuffer ret = new StringBuffer((value < Y42bAgendaConstantes.NUM_16) ? "0" : "");
		ret.append(Integer.toHexString(value).toUpperCase());
		return ret.toString();
	}

}
