package com.classpath.zip;

import com.vmx.AuxClass;
import com.vmx.StringEncoder;
import java.io.*;

class CentralDirectoryEndRecord
{
	public int numEntries,		// total number of entries in the central dir
	           centralSize,		// size of the central directory
			   centralOffset;	// offset of the central directory
	
	public String comment;
	
	public CentralDirectoryEndRecord()
	{
		comment = "";
	}
	
	public boolean read(InputStream is) throws IOException
	{
		if(AuxClass.readLeInt(is) != ZipConstants.ENDSIG)
		{
			return false;
		}
		
		is.skip(6);
		
		numEntries = AuxClass.readLeShort(is);
		centralSize = AuxClass.readLeInt(is);
		centralOffset = AuxClass.readLeInt(is);
		
		int commentLen = AuxClass.readLeShort(is);
		
		if(commentLen > 0)
		{
			comment = StringEncoder.readString(is, commentLen, StringEncoder.ENC_ARCHIVE);
		}
		else
		{
			comment = "";
		}
		
		return true;
	}
	
	public void write(OutputStream os) throws IOException
	{
		AuxClass.writeLeInt(os, ZipConstants.ENDSIG);
		
		AuxClass.writeLeShort(os, 0); /* disk number */
		AuxClass.writeLeShort(os, 0); /* disk with start of central dir */
		AuxClass.writeLeShort(os, numEntries);
		AuxClass.writeLeShort(os, numEntries);
		AuxClass.writeLeInt(os, centralSize);
		AuxClass.writeLeInt(os, centralOffset);
		
		byte[] zipComment = StringEncoder.encodeString(comment, StringEncoder.ENC_ARCHIVE);
		AuxClass.writeLeShort(os, zipComment.length);

		if(zipComment.length > 0)
		{
			os.write(zipComment);
		}
	}
}
