package com.gem.media.splash.base.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
    public static File build(File parent, Object... args) {
        if (args == null) {
            return parent;
        }
        return new File(parent, StringUtil.join(args, "/"));
    }

    public static void createFile(File file) throws Throwable {
        createFolder(file.getParentFile());
    }

    public static void createFolder(File folder) throws Throwable {
        if (folder.isDirectory() || folder.mkdirs()) {
            return;
        }
        throw new Throwable("create folder failed: " + folder.getAbsolutePath());
    }

    public static void deleteFiles(File... files) {
        if (files != null) {
            for (File file : files) {
                deleteFile(file);
            }
        }
    }

    public static void deleteFile(File file) {
        if (file != null && file.exists()) {
            if (file.isDirectory()) {
                deleteFiles(file.listFiles());
            }
            file.delete();
        }
    }

    public static void copyToFolder(File destFolder, File... files) throws Throwable {
        if (files != null) {
            for (File file : files) {
                File target = new File(destFolder, file.getName());
                if (file.isFile()) {
                    copy(target, file);
                } else {
                    copyToFolder(target, file.listFiles());
                }
            }
        }
    }

    public static void copyToFile(File destFile, File file) throws Throwable {
        if (file.exists() && file.isFile()) {
            copy(destFile, file);
        }
    }

    private static void copy(File destFile, File file) throws Throwable {
        createFile(destFile);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(file);
            outputStream = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024 * 8];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        } finally {
            CloseUtil.close(outputStream, inputStream);
        }
    }
}
