/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.jms.message;

import java.util.Random;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;

/**
 * <p/>
 * The MessageID field contains a value that uniquely identifies each message
 * sent by a provider..
 * </p>
 *
 * @author <a href="mailto:founder_chen@yahoo.com.cn">Peter.Cheng</a>
 * @version Revision: 1.1 Date: 2002-11-07 21:08:42
 */

public class MessageID {

    private static Random rand = new Random(System.currentTimeMillis());
    private String id = "";
    private long longID = 0;

    // The prefix for transient messages
    public final static String PREFIX = "ID:";

    // The prefix for persistent messages
    public final static String PERSISTENT_PREFIX = "ID:P";

    /**
     * Create MessageID with special id
     *
     * @param id
     * @throws javax.jms.JMSException an error occurred while message id not start with ID:.
     */
    public MessageID(String id) throws JMSException {
        if(id.startsWith(PERSISTENT_PREFIX)) {
            this.id = id;
            try {
                this.longID =
                        Long.parseLong(id.substring(PERSISTENT_PREFIX.length()));
            }
            catch(NumberFormatException exception) {
                throw new JMSException(id + " is not a valid identity");
            }
        }
        else if(id.startsWith(PREFIX)) {
            this.id = id;
            try {
                this.longID = Long.parseLong(id.substring(PREFIX.length()));
            }
            catch(NumberFormatException exception) {
                throw new JMSException(id + " is not a valid identity");
            }
        }
        else {
            throw new JMSException("The message id must start with ID:");
        }
    }

    /**
     * Construct a message id based on the delivery mode of the message
     *
     * @param mode -
     *             delivery mode
     */
    public MessageID(int mode) {
        longID = Math.abs(rand.nextLong());
        if(mode == DeliveryMode.PERSISTENT) {
            this.id = PERSISTENT_PREFIX + Long.toString(longID);
        }
        else {
            this.id = PREFIX + Long.toString(longID);
        }
    }

    /**
     * Get Message ID
     *
     * @return messageID
     */
    public String getMessageID() {
        return this.id;
    }

    public String toString() {
        return "MessageID : " + this.id;
    }
}
