package org.academiadecodigo.enuminatti.copyfile;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class FileIO {

    private String fileName;

    private final static int BUFFER = 1024;

    public FileIO(String inFile) {
        this.fileName = inFile;
    }

    public void copyToFile(String outFilename) {

        try (FileInputStream inFile = new FileInputStream(fileName);
             FileOutputStream outFile = new FileOutputStream(outFilename)
        ) {
            int bytesRead = BUFFER;
            byte[] buffer = new byte[bytesRead];
            while (bytesRead == BUFFER) {
                bytesRead = inFile.read(buffer);
                outFile.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }

    public static byte[] createMD5Checksum(String fileName) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");

        try (FileInputStream inFile = new FileInputStream(fileName)) {
            int bytesRead = BUFFER;
            byte[] buffer = new byte[bytesRead];
            while (bytesRead == BUFFER) {
                bytesRead = inFile.read(buffer);
                md.update(buffer, 0, bytesRead);
            }

            return md.digest();
        }
    }

    public static String getMD5Checksum(String fileName) throws Exception {
        byte[] digest = createMD5Checksum(fileName);

        StringBuilder res = new StringBuilder();

        for (byte b : digest) {
            res.append(Integer.toString((b & 0xFF) + 0x100, 16).substring(1));
        }

        return res.toString();
    }

}
