package org.eclipse.team.examples.filesystem;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.zip.CRC32;

public class CRCUtils {
	public static long calculateCRC(File inputFile) {
		if (inputFile.isDirectory()) {
			return 10000;
		}
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new FileReader(inputFile));
			StringBuilder stringBuilder = new StringBuilder();
			int value = 0;
			while ((value = bufferedReader.read()) != -1) {
				//
				// Ignora i caratteri di ritorno a capo (CR e LF).
				// if (value == 10 || value == 13) continue;
				//
				// Ignora tutti i caratteri speciali compreso lo spazio (32).
//				if (value > -1 && value < 33) continue;//VN COMMENTO QUESTA ROBA PERCHÉ NON CREDO SIA CORRETTA
				stringBuilder.append(value);
			}
			return calculateCRC(stringBuilder.toString().getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return 0;
	}

	private static long calculateCRC(byte[] content) {
		CRC32 crc = new CRC32();
		crc.update(content);
		return crc.getValue();
	}

	public static boolean equals(byte[] syncBytes, byte[] oldBytes) {
		if (syncBytes == null) {
			if (oldBytes == null) {
				return true;
			} else {
				return false;
			}
		} else {
			if (oldBytes == null) {
				return false;
			}
		} 
		if (syncBytes.length != oldBytes.length) return false;
		for (int i = 0; i < oldBytes.length; i++) {
			if (oldBytes[i] != syncBytes[i]) return false;
		}
		return true;
	}
}
