package com.ttv.acs.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;



/**
 * Create MD5 checksum. Extracted from adiTransferAMS project com.enterprisedt.net.ftp.TTVFTPClient
 * 
 * @author cmao
 * 
 */
public class ChecksumUtil {

	private final static Logger logger = Logger.getLogger(ChecksumUtil.class); 
	public static final String DEFAULT_CHECKSUM_ALGORITHM = "MD5";
	final private static int DEFAULT_BUFFER_SIZE = 16384;

	public static String getCheckSum(String contentFilePath) throws NoSuchAlgorithmException, IOException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(contentFilePath));

		MessageDigest md = null;

		byte[] ckba = null;

		String chksum = "";

		md = MessageDigest.getInstance(DEFAULT_CHECKSUM_ALGORITHM);

		ckba = new byte[md.getDigestLength()];

		byte[] chunk = new byte[DEFAULT_BUFFER_SIZE];

		int count;
		try {
			while ((count = readChunk(in, chunk, DEFAULT_BUFFER_SIZE)) >= 0) {
				md.update(chunk, 0, count);
			}
		} catch (IOException e) {
			logger.error(e);
			throw e;
		}finally{
			if(in != null){
				in.close();
			}
		}

		ckba = md.digest();

		for (int i = 0; i < ckba.length; i++) {

			long x = new Byte(ckba[i]).longValue();

			String s = "0" + Long.toHexString(x);

			chksum = chksum + s.substring(s.length() - 2);

		}

		return chksum;
	}

	protected static int readChunk(BufferedInputStream in, byte[] chunk, int chunksize) throws IOException {

		return in.read(chunk, 0, chunksize);

	}
}
