package info.knacki.pass.io;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;

public class FileUtils {
    private static final Logger log = Logger.getLogger(FileUtils.class.getName());

    public static void Rmdir(File f) {
        if (!f.isDirectory()) {
            FileUtils.DeleteFile(f);
        }
        else {
            for (File i : f.listFiles())
                Rmdir(i);
            FileUtils.DeleteFile(f);
        }
    }

    public static byte[] ReadAllStream(InputStream s) throws IOException {
        ByteArrayOutputStream str = new ByteArrayOutputStream();
        pipe(s, str);
        return str.toByteArray();
    }

    public static String ReadAllFile(File file) throws IOException {
        BufferedReader buf = new BufferedReader(new FileReader(file));
        StringBuilder result = new StringBuilder();
        String tmp;

        while ((tmp = buf.readLine()) != null) {
            if (result.length() > 0)
                result.append("\n");
            result.append(tmp);
        }
        buf.close();
        return result.toString();
    }

    public static void pipe(InputStream in, OutputStream out) throws IOException {
        int len;
        byte[] buf = new byte[1024];
        do {
            len = in.read(buf, 0, 1024);
            if (len > 0) {
                out.write(buf, 0, len);
            }
        } while (len > 0);
    }

    public static String TrimExtension(String in) {
        int lastIndex = in.lastIndexOf('.');
        if (lastIndex >= Math.max(in.length() -5, 0))
            return in.substring(0, lastIndex);
        return in;
    }

    public static void TrashFile(File f) {
        if (PathUtils.IsHidden(f.getAbsolutePath())) {
            if (!f.delete())
                log.severe("Cannot remove file " +f.getAbsolutePath());
        } else {
            final String dest = PathUtils.HiddenPath(f.getAbsolutePath());

            if (!f.renameTo(new File(dest)))
                log.severe("Cannot rename file " +f.getAbsolutePath() +" to " +dest);
        }
    }

    public static void RestoreFile(File f) {
        if (PathUtils.IsHidden(f.getAbsolutePath())) {
            final String dest = PathUtils.UnHiddenPath(f.getAbsolutePath());
            if (!f.renameTo(new File(dest)))
                log.severe("Cannot rename file " + f.getAbsolutePath() + " to " + dest);
        }
    }

    public static void Touch(File f) throws IOException {
        f.createNewFile();
    }

    public static void DeleteFile(File f) {
        f.delete();
    }

    public static void MkDir(File f, boolean recursive) {
        if (recursive)
            f.mkdirs();
        else
            f.mkdir();
    }
}
