package gov.va.vinci.dart.common;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Random;

/** Automatically generate a message id based on the serialVersionUID property of a
 * derived class.  
 * @author 
 *
 */
public class MessageIdGenerator {
	protected long messageIdCounter = 1L;
	private long targetSerialVersionUIDField;
	private Serializable serializable;

	public MessageIdGenerator(Serializable serializable) {
		this.serializable = serializable;
		
		try {
			Field serialVersionUIDField = serializable.getClass().getDeclaredField("serialVersionUID");
			
			serialVersionUIDField.setAccessible(true);
			Long longInstance = (Long)serialVersionUIDField.get(this);
			
			targetSerialVersionUIDField = longInstance.longValue();

			Random generator = new Random(System.currentTimeMillis());
			messageIdCounter = targetSerialVersionUIDField + generator.nextLong();
			
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	protected long nextMessageId() {
		long nextIdVal = 0L;
		
		synchronized(serializable) {
			nextIdVal = messageIdCounter++;
		}
 
		return nextIdVal;
	}
}
