/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activeblaze.wire;

import org.apache.activeblaze.BlazeMessage;
import org.apache.activeblaze.BlazeMessageFormatException;
import org.apache.activeblaze.BlazeRuntimeException;
import org.apache.activeblaze.jms.BlazeJmsDestination;
import org.apache.activeblaze.util.Callback;

import javax.jms.*;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Implementation of a Jms Message
 */
public class BlazeJmsMessage extends BlazeMessage implements Message {

    protected enum JmsMessageType {MESSAGE, BYTES, MAP, OBJECT, STREAM, TEXT}

    protected transient Callback<BlazeJmsMessage> acknowledgeCallback;
    protected transient BlazeJmsDestination jmsDestination;
    protected transient BlazeJmsDestination jmsReplyToDestination;
    protected Buffer payload;

    public BlazeJmsMessage() {
        setNoLocal(true);
    }

    /**
     * Get the packetType
     *
     * @return the packetType
     */
    public int getPacketType() {
        return PacketType.JMS_MESSAGE.getNumber();
    }

    /**
     * @return clone of a BlazeMessage
     * @see org.apache.activeblaze.BlazeMessage#clone()
     */
    public BlazeJmsMessage clone() {
        BlazeJmsMessage copy = new BlazeJmsMessage();
        try {
            copy(copy);
        } catch (Exception e) {
            throw new BlazeRuntimeException(e);
        }
        return copy;
    }

    protected void copy(BlazeJmsMessage copy) throws IOException {
        super.copy(copy);
        copy.acknowledgeCallback = this.acknowledgeCallback;
        copy.jmsDestination = this.jmsDestination;
        copy.jmsReplyToDestination = this.jmsReplyToDestination;
    }

    /**
     * @return the type
     * @see org.apache.activeblaze.BlazeMessage#getType()
     */
    public int getType() {
        return JmsMessageType.MESSAGE.ordinal();
    }

    /**
     * @return the acknowledge <Code>Callback</Code>
     */
    public Callback<BlazeJmsMessage> getAcknowledgeCallback() {
        return this.acknowledgeCallback;
    }

    /**
     * @param acknowledgeCallback
     */
    public void setAcknowledgeCallback(Callback<BlazeJmsMessage> acknowledgeCallback) {
        this.acknowledgeCallback = acknowledgeCallback;
    }

    /**
     * @see javax.jms.Message#acknowledge()
     */
    public void acknowledge() {
        Callback<BlazeJmsMessage> callback = this.acknowledgeCallback;
        if (callback != null) {
            callback.execute(this);
        }
    }

    /**
     * @see javax.jms.Message#clearBody()
     */
    public void clearBody() throws JMSException {
        this.payload = null;
    }

    /**
     * @see javax.jms.Message#clearProperties()
     */
    public void clearProperties() {
        super.clear();
    }

    /**
     * @return boolean value
     * @see javax.jms.Message#getBooleanProperty(java.lang.String)
     */
    public boolean getBooleanProperty(String name) throws JMSException {
        try {
            return getBooleanValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return byte value
     * @see javax.jms.Message#getByteProperty(java.lang.String)
     */
    public byte getByteProperty(String name) throws JMSException {
        try {
            return getByteValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return double value
     * @see javax.jms.Message#getDoubleProperty(java.lang.String)
     */
    public double getDoubleProperty(String name) throws JMSException {
        try {
            return getDoubleValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return float value
     * @see javax.jms.Message#getFloatProperty(java.lang.String)
     */
    public float getFloatProperty(String name) throws JMSException {
        try {
            return getFloatValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return int value
     * @see javax.jms.Message#getIntProperty(java.lang.String)
     */
    public int getIntProperty(String name) throws JMSException {
        try {
            return getIntValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return String value
     * @see javax.jms.Message#getJMSCorrelationID()
     */
    public String getJMSCorrelationID() {
        return getCorrelationId();
    }

    /**
     * @return correlationId as bytes
     * @see javax.jms.Message#getJMSCorrelationIDAsBytes()
     */
    public byte[] getJMSCorrelationIDAsBytes() {
        return getCorrelationId() != null ? getCorrelationId().getBytes() : null;
    }

    /**
     * @return the deliveryMode
     * @see javax.jms.Message#getJMSDeliveryMode()
     */
    public int getJMSDeliveryMode() {
        return isPersistent() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT;
    }

    /**
     * @return the JMSDestination
     * @see javax.jms.Message#getJMSDestination()
     */
    public Destination getJMSDestination() {
        if (this.jmsDestination == null) {
            this.jmsDestination = BlazeJmsDestination.createJmsDestination(getDestination());
        }
        return this.jmsDestination;
    }

    /**
     * @return the expiration
     * @see javax.jms.Message#getJMSExpiration()
     */
    public long getJMSExpiration() {
        return getExpiration();
    }

    /**
     * @return the messageId
     * @see javax.jms.Message#getJMSMessageID()
     */
    public String getJMSMessageID() {
        return getMessageId();
    }

    /**
     * @see javax.jms.Message#getJMSPriority()
     */
    public int getJMSPriority() throws JMSException {
        return getPriority();
    }

    /**
     * @see javax.jms.Message#getJMSRedelivered()
     */
    public boolean getJMSRedelivered() throws JMSException {
        return getRedeliveryCounter() > 0;
    }

    /**
     * @see javax.jms.Message#getJMSReplyTo()
     */
    public Destination getJMSReplyTo() throws JMSException {
        if (this.jmsReplyToDestination == null) {
            this.jmsReplyToDestination = BlazeJmsDestination.createJmsDestination(getReplyTo());
        }
        return this.jmsReplyToDestination;
    }

    /**
     * @return timestamp
     * @see javax.jms.Message#getJMSTimestamp()
     */
    public long getJMSTimestamp() {
        return getTimeStamp();
    }

    /**
     * @return the message type
     * @see javax.jms.Message#getJMSType()
     */
    public String getJMSType() throws JMSException {
        return getMessageType();
    }

    /**
     * @see javax.jms.Message#getLongProperty(java.lang.String)
     */
    public long getLongProperty(String name) throws JMSException {
        try {
            return getLongValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return the associated object
     * @see javax.jms.Message#getObjectProperty(java.lang.String)
     */
    public Object getObjectProperty(String name) {
        return getObjectValue(name);
    }

    /**
     * @return property names
     * @see javax.jms.Message#getPropertyNames()
     */
    public Enumeration<String> getPropertyNames() {
        return getNames();
    }

    /**
     * @return short property
     * @see javax.jms.Message#getShortProperty(java.lang.String)
     */
    public short getShortProperty(String name) throws JMSException {
        try {
            return getShortValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return String property
     * @see javax.jms.Message#getStringProperty(java.lang.String)
     */
    public String getStringProperty(String name) throws JMSException {
        try {
            return getStringValue(name);
        } catch (BlazeMessageFormatException e) {
            throw new MessageFormatException(e.getMessage());
        }
    }

    /**
     * @return true if the property exists
     * @see javax.jms.Message#propertyExists(java.lang.String)
     */
    public boolean propertyExists(String name) {
        return valueExists(name);
    }

    /**
     * @see javax.jms.Message#setBooleanProperty(java.lang.String, boolean)
     */
    public void setBooleanProperty(String name, boolean value) {
        setBooleanValue(name, value);
    }

    /**
     * @see javax.jms.Message#setByteProperty(java.lang.String, byte)
     */
    public void setByteProperty(String name, byte value) {
        setByteValue(name, value);
    }

    /**
     * @see javax.jms.Message#setDoubleProperty(java.lang.String, double)
     */
    public void setDoubleProperty(String name, double value) {
        setDoubleValue(name, value);
    }

    /**
     * @see javax.jms.Message#setFloatProperty(java.lang.String, float)
     */
    public void setFloatProperty(String name, float value) {
        setFloatValue(name, value);
    }

    /**
     * @see javax.jms.Message#setIntProperty(java.lang.String, int)
     */
    public void setIntProperty(String name, int value) {
        setIntValue(name, value);
    }

    /**
     * @see javax.jms.Message#setJMSCorrelationID(java.lang.String)
     */
    public void setJMSCorrelationID(String correlationID) {
        setCorrelationId(correlationID);
    }

    /**
     * @see javax.jms.Message#setJMSCorrelationIDAsBytes(byte[])
     */
    public void setJMSCorrelationIDAsBytes(byte[] correlationID) {
        setCorrelationId(new String(correlationID));
    }

    /**
     * @see javax.jms.Message#setJMSDeliveryMode(int)
     */
    public void setJMSDeliveryMode(int deliveryMode) {
        boolean value = deliveryMode == DeliveryMode.PERSISTENT;
        setPersistent(value);
    }

    /**
     * @see javax.jms.Message#setJMSDestination(javax.jms.Destination)
     */
    public void setJMSDestination(javax.jms.Destination destination) throws JMSException {
        this.jmsDestination = BlazeJmsDestination.transform(destination);
    }

    /**
     * @see javax.jms.Message#setJMSExpiration(long)
     */
    public void setJMSExpiration(long expiration) {
        setExpiration(expiration);
    }

    /**
     * @see javax.jms.Message#setJMSMessageID(java.lang.String)
     */
    public void setJMSMessageID(String id) {
        setId(id);
    }

    /**
     * @see javax.jms.Message#setJMSPriority(int)
     */
    public void setJMSPriority(int priority) {
        setPriority(priority);
    }

    /**
     * @see javax.jms.Message#setJMSRedelivered(boolean)
     */
    public void setJMSRedelivered(boolean redelivered) {
    }

    /**
     * @see javax.jms.Message#setJMSReplyTo(javax.jms.Destination)
     */
    public void setJMSReplyTo(Destination replyTo) throws JMSException {
        this.jmsReplyToDestination = BlazeJmsDestination.transform(replyTo);
    }

    /**
     * @see javax.jms.Message#setJMSTimestamp(long)
     */
    public void setJMSTimestamp(long timestamp) {
        setTimeStamp(timestamp);
    }

    /**
     * @see javax.jms.Message#setJMSType(java.lang.String)
     */
    public void setJMSType(String type) {
        setMessageType(type);
    }

    /**
     * @see javax.jms.Message#setLongProperty(java.lang.String, long)
     */
    public void setLongProperty(String name, long value) {
        setLongValue(name, value);
    }

    /**
     * @see javax.jms.Message#setObjectProperty(java.lang.String, java.lang.Object)
     */
    public void setObjectProperty(String name, Object value) {
        put(name, value);
    }

    /**
     * @see javax.jms.Message#setShortProperty(java.lang.String, short)
     */
    public void setShortProperty(String name, short value) {
        setShortValue(name, value);
    }

    /**
     * @see javax.jms.Message#setStringProperty(java.lang.String, java.lang.String)
     */
    public void setStringProperty(String name, String value) {
        setStringValue(name, value);
    }

    protected void storeContent() throws IOException {
        if (this.jmsDestination != null) {
            super.setDestination(this.jmsDestination.getDestination());
        }
        if (this.jmsReplyToDestination != null) {
            super.setReplyTo(this.jmsReplyToDestination.getDestination());
        }
        super.storeContent();
    }

    public void read(BufferInputStream in) throws IOException {
        super.read(in);
        this.payload = in.readBuffer();
    }

    /**
     * Write state to a Buffer
     */
    public void write(BufferOutputStream out) throws IOException {
        super.write(out);
        out.write(this.payload);
    }

    public String toString() {
        return "[" + getMessageType() + "]" + getMessageId();
    }

}
