package com.koobietech.eas.common.utils;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;

public class FileManager {
    public boolean saveDocument(XWPFDocument document, String savePath){
        boolean ret = true;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(savePath);
            document.write(fileOutputStream);
        } catch (IOException e) {
            ret = false;
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {}
        }
        return ret;
    }

    public boolean saveDocument(XWPFDocument document, String savePath, String fileName){
        return saveDocument(document, savePath + fileName);
    }

    public boolean createPath(String path){
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        return true;
    }

    public boolean saveFile(InputStream stream, String savePath){
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(savePath);
            int bytesRead;
            byte[] buffer = new byte[1024];
            while ((bytesRead = stream.read(buffer)) != -1){
                fileOutputStream.write(bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            }catch (IOException e){}
        }
        return true;
    }

    public boolean saveFile(InputStream  stream, String savePath, String fileName) {
        return saveFile(stream, savePath + fileName);
    }

    public boolean isFileExists(String filePath){
        File file = new File(filePath);
        return file.exists();
    }

    public boolean deleteFile(String filePath){
        File file = new File(filePath);
        return file.delete();
    }

    public boolean isFolderExists(String folderPath){
        File file = new File(folderPath);
        return file.exists();
    }

    public boolean createFolder(String folderPath){
        File file = new File(folderPath);
        return file.mkdirs();
    }

    public boolean deleteFolder(String folderPath){
        File file = new File(folderPath);
        return file.delete();
    }

    public boolean copyFile(String srcFilePath, String destFilePath){
        File srcFile = new File(srcFilePath);
        File destFile = new File(destFilePath);
        return srcFile.renameTo(destFile);
    }

    public boolean moveFile(String srcFilePath, String destFilePath){
        File srcFile = new File(srcFilePath);
        File destFile = new File(destFilePath);
        return srcFile.renameTo(destFile);
    }
}
