package eu.dnetlib.installer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * This class implements a static utility method.
 * @author thanos
 *
 */
public class Utils {
	private static final int BUFFER_SIZE = 1024;
	
	/**
	 * Copy a file to another.
	 * @param source the source file to copy data from
	 * @param destination the destination file to copy data to
	 * @throws IOException if any I/O errors occur
	 */
	public static void copyFile(File source, File destination) throws IOException {
		FileInputStream fileInputStream  = new FileInputStream(source);
		FileOutputStream fileOutputStream = new FileOutputStream(destination);
		byte [] buffer = new byte[BUFFER_SIZE];
		int i = 0;
		try {
			while ((i = fileInputStream.read(buffer)) != -1)
				fileOutputStream.write(buffer, 0, i);
		} finally {
			fileInputStream.close();
			fileOutputStream.close();
		}
	}
	
	/**
	 * Get all the contents of a directory recursively.
	 * @param directory the directory of which to retrieve contents
	 * @return a list of the files and directories in the directory
	 */
	public static List<File> getAllContents(File directory) {
		List<File> result = new ArrayList<File>();
		if (directory.isDirectory()) {
			for (String fileName : directory.list()) {
				File file = new File(directory + File.separator + fileName);
				result.addAll(Utils.getAllContents(file));
				result.add(file);
			}
		}
		return result;
	}
}
