/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.file.Files;

/**
 *
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public final class FileUtils {
    
    private FileUtils() {
        /* utility class */
    }
    
    public static void delete(File file) throws IOException {
        if(!file.exists()) { 
			return; 
		}
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			if(null != files) {
				for(File s : files) {
					delete(s);
				}
			}
		}
		Files.delete(file.toPath());
    }
    
    public static byte[] content(File file) throws IOException {
        try (RandomAccessFile istream = new RandomAccessFile(file, "r")) {
            byte[] content = new byte[ (int)istream.length() ];
            istream.readFully(content);
            return content;
        }
    }
    
    /**
     * Compare content of files.
     * @param file1
     * @param file2
     * @return 
     */
    public static boolean equivalent(File file1, File file2) throws IOException {
        if(file1.equals(file2)) {
			return true;
		}
        if(file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
            return true;
        }
		if(file1.length() != file2.length()) {
			return false;
		}
        try(
            InputStream istream1=new FileInputStream(file1);
            InputStream istream2=new FileInputStream(file2);
            ) {
            return IOStreams.equivalent(istream1, istream2);
        }
    }
    
}
