package com.engine.htsc.doc.util;

import org.apache.commons.lang3.StringUtils;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;

import javax.ws.rs.WebApplicationException;
import java.io.*;
import java.util.zip.ZipInputStream;

public class IoUtil {

    public InputStream getInputStreamByPath (String realfilepath,String iszip) throws IOException {
        InputStream inputStream = null;
        ZipInputStream zipInputStream = null;
        if (StringUtils.isNotBlank(realfilepath)) {
            File file = new File(realfilepath);
            if(!file.exists())
            {
                throw  new WebApplicationException(404);
            }
            if (iszip.equals("1")) {
                zipInputStream = new ZipInputStream(new FileInputStream(file));
                if (zipInputStream.getNextEntry() != null) {
                    inputStream = new BufferedInputStream(zipInputStream);
                }
            } else {
                inputStream = new BufferedInputStream(new FileInputStream(file));
            }
        }
        if(inputStream !=null){
            inputStream.close();
        }
        if(zipInputStream !=null){
            inputStream.close();
        }
        return inputStream;
    }

    public File generateFile(int imagefileid,String imagefilename) throws IOException {
        InputStream inputstream = ImageFileManager.getInputStreamById(imagefileid);
        int index;
        byte[] bytes = new byte[1024];
        // 文件夹名称
        String path = "/app/ecology/filesystem/xcoa";
        // linux 下 先创建文件夹
        File dir = new File(path);
        //设置写权限，windows下不用此语句
        dir.setWritable(true, false);
        dir.mkdirs();
        //赋权限
        Runtime.getRuntime().exec("chmod -R 777 " + path);
        //每次写文件时先删除历史文件
        deleteFile(dir);
        path += "/"+imagefilename;//创建文件
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        FileOutputStream uploadFile = new FileOutputStream(file);
        while ((index = inputstream.read(bytes)) != -1) {
            uploadFile.write(bytes, 0, index);
            uploadFile.flush();
        }
        inputstream.close();
        uploadFile.close();
        Runtime.getRuntime().exec("chmod -R 777 " + path);
        return file;
    }


    /**
     * 删除某个文件夹下面的所有文件
     * @param file
     */
    public static void deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //打印文件名
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                deleteFile(f);
            } else {
                f.delete();
            }
        }
    }


}
