/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed 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.codehaus.activemq.io.impl;
import java.io.DataOutput;
import java.io.IOException;
import org.codehaus.activemq.message.AbstractPacket;
import org.codehaus.activemq.message.ActiveMQDestination;
import org.codehaus.activemq.message.ActiveMQMessage;
import org.codehaus.activemq.message.Packet;
import org.codehaus.activemq.util.BitArray;

/**
 * Writes a ProducerInfo object to a Stream
 */
public class ActiveMQMessageWriter extends AbstractPacketWriter {
    /**
     * Return the type of Packet
     * 
     * @return integer representation of the type of Packet
     */
    public int getPacketType() {
        return Packet.ACTIVEMQ_MESSAGE;
    }

    /**
     * Write a Packet instance to data output stream
     *
     * @param packet  the instance to be seralized
     * @param dataOut the output stream
     * @throws IOException thrown if an error occurs
     */
    public void writePacket(Packet packet, DataOutput dataOut) throws IOException {
        ActiveMQMessage msg = (ActiveMQMessage) packet;
        byte[] payload = msg.getBodyAsBytes();
        
        BitArray ba = msg.getBitArray();
        ba.reset();
        writeUTF(msg.getId(),dataOut);
        ba.set(AbstractPacket.RECEIPT_REQUIRED_INDEX, packet.isReceiptRequired());
        Object[] visited = msg.getBrokersVisited();
        boolean writeVisited = visited != null && visited.length > 0;
        ba.set(AbstractPacket.BROKERS_VISITED_INDEX,writeVisited);
        ba.set(ActiveMQMessage.CORRELATION_INDEX, msg.getJMSCorrelationID() != null);
        ba.set(ActiveMQMessage.TYPE_INDEX, msg.getJMSType() != null);
        ba.set(ActiveMQMessage.BROKER_NAME_INDEX, msg.getEntryBrokerName() != null);
        ba.set(ActiveMQMessage.CLUSTER_NAME_INDEX, msg.getEntryClusterName() != null);
        ba.set(ActiveMQMessage.TRANSACTION_ID_INDEX, msg.getTransactionId() != null);
        ba.set(ActiveMQMessage.REPLY_TO_INDEX, msg.getJMSReplyTo() != null);
        ba.set(ActiveMQMessage.TIMESTAMP_INDEX, msg.getJMSTimestamp() > 0);
        ba.set(ActiveMQMessage.EXPIRATION_INDEX, msg.getJMSExpiration() > 0);
        ba.set(ActiveMQMessage.REDELIVERED_INDEX, msg.getJMSRedelivered());
        ba.set(ActiveMQMessage.XA_TRANS_INDEX, msg.isXaTransacted());
        ba.set(ActiveMQMessage.CID_INDEX, msg.getConsumerNos() != null);
        ba.set(ActiveMQMessage.PROPERTIES_INDEX, msg.getProperties() != null && msg.getProperties().size() > 0);
        ba.set(ActiveMQMessage.DISPATCHED_FROM_DLQ_INDEX,msg.isDispatchedFromDLQ());
        ba.set(ActiveMQMessage.PAYLOAD_INDEX, payload != null);
        
        ba.writeToStream(dataOut);
        if (writeVisited){
            dataOut.writeShort(visited.length);
            for(int i =0; i < visited.length; i++){
                dataOut.writeUTF(visited[i].toString());
            }
        }
       
        super.writeUTF(msg.getJMSClientID(), dataOut);
        super.writeUTF(msg.getProducerID(), dataOut);
        ActiveMQDestination.writeToStream((ActiveMQDestination) msg.getJMSDestination(), dataOut);
        dataOut.write(msg.getJMSDeliveryMode());
        dataOut.write(msg.getJMSPriority());

        

        if (ba.get(ActiveMQMessage.CORRELATION_INDEX)) {
            super.writeUTF(msg.getJMSCorrelationID(), dataOut);
        }
        if (ba.get(ActiveMQMessage.TYPE_INDEX)) {
            super.writeUTF(msg.getJMSType(), dataOut);
        }
        if (ba.get(ActiveMQMessage.BROKER_NAME_INDEX)) {
            super.writeUTF(msg.getEntryBrokerName(), dataOut);
        }
        if (ba.get(ActiveMQMessage.CLUSTER_NAME_INDEX)) {
            super.writeUTF(msg.getEntryClusterName(), dataOut);
        }
        if (ba.get(ActiveMQMessage.TRANSACTION_ID_INDEX)) {
            super.writeUTF(msg.getTransactionId(), dataOut);
        }
        if (ba.get(ActiveMQMessage.REPLY_TO_INDEX)) {
            ActiveMQDestination.writeToStream((ActiveMQDestination) msg.getJMSReplyTo(), dataOut);
        }
        if (ba.get(ActiveMQMessage.TIMESTAMP_INDEX)) {
            dataOut.writeLong(msg.getJMSTimestamp());
        }
        if (ba.get(ActiveMQMessage.EXPIRATION_INDEX)) {
            dataOut.writeLong(msg.getJMSExpiration());
        }
        if (ba.get(ActiveMQMessage.CID_INDEX)) {
            //write out consumer numbers ...
            int[] cids = msg.getConsumerNos();
            dataOut.writeShort(cids.length);
            for (int i = 0; i < cids.length; i++) {
                dataOut.writeShort(cids[i]);
            }
        }
        if (ba.get(ActiveMQMessage.PROPERTIES_INDEX)) {
            msg.writeMapProperties(msg.getProperties(), dataOut);
        }
        if (ba.get(ActiveMQMessage.PAYLOAD_INDEX)) {
            dataOut.writeInt(payload.length);
            dataOut.write(payload);
        }
        
        if (wireFormatVersion >= 2){
            dataOut.writeLong(msg.getSequenceNumber());
            dataOut.writeByte(msg.getDeliveryCount());
        }
    }
}
