/**
 *
 * Copyright 2004 Hiram Chirino
 *
 * 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.journal.impl;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Serializes/Deserializes record header information. 
 * 
 * @version $Revision: 1.1 $
 */
public class RecordHeader {
    static final public int RECORD_HEADER_SIZE=16;
    static final public byte[] START_OF_RECORD 	= new byte[] { 'S', 'o', 'R' }; 

    public int length;
    public long sequenceId;
    public byte recordType;

	/**
	 * @return
	 */
	public ByteBuffer toByteBuffer() {
		ByteBuffer buff = ByteBuffer.allocate(RECORD_HEADER_SIZE);
		buff.put(START_OF_RECORD)
		 	.putInt(length)
			.putLong(sequenceId)
			.put(recordType)
			.flip();
		return buff;
	}

	void writeRecordHeader( DataOutput out ) throws IOException {
	    out.write(START_OF_RECORD);
	    out.writeInt(length);
	    out.writeLong(sequenceId);
	    out.writeByte(recordType);
	}
	
	void readRecordHeader( DataInput in ) throws IOException {
        for (int i = 0; i < START_OF_RECORD.length; i++) {
            byte checkByte = START_OF_RECORD[i];
            if( in.readByte()!= checkByte ) {
                throw new IOException("Not a valid record header.");
            }
        }
        length = in.readInt();
        sequenceId = in.readLong();
        recordType = in.readByte();
	}

	/**
	 * 
	 */
	public void invalidate() {
		length=-1;
		sequenceId=-1;			
	}
	
	public boolean isValid() {
		return length>=0;
	}

	/**
	 * @param recordType2
	 * @param sequenceId2
	 * @param data
	 */
	public void bulkSet(byte recordType, long sequenceId, byte[] data) {
	    this.length = data.length;
	    this.sequenceId = sequenceId;
	    this.recordType = recordType;
	}

}