import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class HashCmd {
	
	public static Digest get_hash_algorithm(String algorithm_name){
		if(algorithm_name.equalsIgnoreCase("md4")){ return new MD4();}
		if(algorithm_name.equalsIgnoreCase("md5")){ return new MD5();}
		if(algorithm_name.equalsIgnoreCase("sha1")){ return new Sha160();}
		if(algorithm_name.equalsIgnoreCase("ripemd160")){ return new RipeMD160();}
		return null;
	}
		
	public static void main(String[] args) {
		long execution_time = 0; 
		int offset = 0; 
		int numRead = 0;
		Digest hash_algorithm = get_hash_algorithm(args[0]); 
		File file = new File(args[1]); 
        
		try {
		    FileInputStream fileInputStream = new FileInputStream(file);
		    int length_to_read = hash_algorithm.blockSize();
		    if (file.length() - offset < hash_algorithm.blockSize()){
		    	length_to_read = (int)(file.length() - offset);
		    }
		    byte[] input_block = new byte[length_to_read];
		    while (offset < file.length() 
		    		&& (numRead=fileInputStream.read(input_block, 0, length_to_read)) >= 0) {
		    	
		    	//long begining_time = System.nanoTime();
		    	long begining_time = System.currentTimeMillis();
				hash_algorithm.update(input_block);
				//execution_time += System.nanoTime() - begining_time;
				execution_time += (System.currentTimeMillis() - begining_time);
 	
		    	offset += numRead;
			    if (file.length() - offset < hash_algorithm.blockSize()){
			    	length_to_read = (int)(file.length() - offset);
			    }
			    input_block = new byte[length_to_read];
		    } 
		    //long begining_time = System.nanoTime();
		    long begining_time = System.currentTimeMillis();
			byte[]message_digest = hash_algorithm.digest();
			//execution_time += System.nanoTime() - begining_time;
			execution_time += System.currentTimeMillis() - begining_time;
			System.out.println("\nRezultat: " + Main.toString(message_digest));
			System.out.println("Vreme: " + execution_time + " ms");
		}
		catch (FileNotFoundException e) {
		    System.out.println("File Not Found.");
		    e.printStackTrace();
		}
		catch (IOException e1){
		    System.out.println("Error Reading The File.");
		    e1.printStackTrace();
		}
    }
}

