/**
 *
 * 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;
import java.util.zip.CRC32;

/**
 * Serializes/Deserializes record header information. 
 * 
 * @version $Revision: 1.1 $
 */
public class RecordFooter {
	
	static final public int SELECTED_CHECKSUM_ALGORITHIM;
	static final public int NO_CHECKSUM_ALGORITHIM=0;
	static final public int HASH_CHECKSUM_ALGORITHIM=1;
	static final public int CRC32_CHECKSUM_ALGORITHIM=2;
	
	static {
		String type = System.getProperty("org.codehaus.activemq.journal.impl.SELECTED_CHECKSUM_ALGORITHIM", "hash");
		if( "none".equals(type) ) {
			SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM;			
		} else if( "crc32".equals(type) ) {
			SELECTED_CHECKSUM_ALGORITHIM = CRC32_CHECKSUM_ALGORITHIM;			
		} else if( "hash".equals(type) ) {
			SELECTED_CHECKSUM_ALGORITHIM = HASH_CHECKSUM_ALGORITHIM;			
		} else {
			System.err.println("System property 'org.codehaus.activemq.journal.impl.SELECTED_CHECKSUM_ALGORITHIM' not set properly.  Valid values are: 'none', 'hash', or 'crc32'");
			SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM;			
		}
	}
	
    static final public int RECORD_FOOTER_SIZE=19;
    static final public byte[] END_OF_RECORD 	= new byte[] { 'E', 'o', 'R' }; 

    public long checksum;
    public long sequenceId;

	/**
	 * @return
	 */
	public ByteBuffer toByteBuffer() {
		ByteBuffer buff = ByteBuffer.allocate(RECORD_FOOTER_SIZE);
		buff.putLong(checksum)
		 	.putLong(sequenceId)
			.put(END_OF_RECORD)
			.flip();
		return buff;
	}

	void writeRecordFooter( DataOutput out ) throws IOException {
	    out.writeLong(checksum);
	    out.writeLong(sequenceId);
	    out.write(END_OF_RECORD);
	}
	
	void readRecordFooter( DataInput in ) throws IOException {
        checksum = in.readLong();
        sequenceId = in.readLong();
        for (int i = 0; i < END_OF_RECORD.length; i++) {
            byte checkByte = END_OF_RECORD[i];
            if( in.readByte()!= checkByte ) {
                throw new IOException("Not a valid record header.");
            }
        }
	}

	/**
	 * 
	 */
	public void invalidate() {
		checksum=-1;
		sequenceId=-1;			
	}
	
	public boolean matches(RecordHeader header) {
		return header.sequenceId==sequenceId;
	}

	static public boolean isChecksumingEnabled() {
		return SELECTED_CHECKSUM_ALGORITHIM!=NO_CHECKSUM_ALGORITHIM;
	}
	
	public boolean matches(byte data[]) {
		return buildChecksum(data)==checksum;
	}

	static public long buildChecksum(byte[] data) {		
		if( SELECTED_CHECKSUM_ALGORITHIM==HASH_CHECKSUM_ALGORITHIM ) {
			byte rc[] = new byte[8];
			for (int i = 0; i < data.length; i++) {
				rc[i%8] ^= data[i];			
			}
			return (rc[0])|(rc[1]<<1)|(rc[2]<<2)|(rc[3]<<3)|(rc[4]<<4)|(rc[5]<<5)|(rc[6]<<6)|(rc[7]<<7) ;
		} else if( SELECTED_CHECKSUM_ALGORITHIM==CRC32_CHECKSUM_ALGORITHIM ) {
			CRC32 crc32 = new CRC32();
			crc32.update(data);
			return crc32.getValue();
		} else {
			return 0L;
		}
	}

	/**
	 * @param header
	 * @param data
	 */
	public void bulkSet(RecordHeader header, byte[] data) {
		this.sequenceId = header.sequenceId;
		this.checksum = buildChecksum(data);
	}

}