package vut.msa.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;

/**
 * Trieda s pomocnymi metodami pre pracu so subormi
 */
public final class FileUtilities {

    private static final Logger log = Logger.getLogger(FileUtilities.class);

    public static void copyFolder(File src, File dest)
            throws IOException {

        if (src.isDirectory()) {

            if (!dest.exists()) {
                dest.mkdir();
                log.info("Adresar prekopirovany.");
            }

            String files[] = src.list();
            for (String file : files) {
                File srcFile = new File(src, file);
                File destFile = new File(dest, file);
                copyFolder(srcFile, destFile);
            }

        } else {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }

            in.close();
            out.close();
            log.info("Subor prekopirovany " + src + " do " + dest);
        }
    }

    public static boolean deleteDirectory(File path) {
        if (path.exists()) {
            File[] files = path.listFiles();
            for (File f : files) {
                if (f.isDirectory()) {
                    deleteDirectory(f);
                } else {
                    f.delete();
                    log.info("Zmazane " + f.getName());
                }
            }
        }
        return (path.delete());
    }

    /**
     * Metoda vrati naformatovany retazec datumu v tvare, ktory je zadany
     * v parametri.Sluzi pre vytvaranie nazvu suboru, pri ukladani zalohy.
     *
     * @param format format, v akom ma byt naformatovany datum
     * @return naformatovany dnesny datum
     */
    public static String getFileDate(String format) {

        SimpleDateFormat f = new SimpleDateFormat(format);
        Date today = new Date();

        return f.format(today);
    }
}
