package net.northking.cctp.daemon.utils;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class FileUtils
{
  public static void copyFolder(File sourceFolder, File targetFolder) throws IOException
  {
    File[] sourceChildren = sourceFolder.listFiles();
    for (File sourceChild : sourceChildren)
    {
      File targetFile = new File(targetFolder, sourceChild.getName());
      if (sourceChild.isDirectory())
      {
        targetFile.mkdirs();
        copyFolder(sourceChild, targetFile);
      } else
      {
        copyFile(sourceChild, targetFile);
      }
    }
  }

  public static void copyFile(File sourceChild, File targetFile) throws IOException
  {
    copy(new FileInputStream(sourceChild), new FileOutputStream(targetFile));
  }

  public static void unZip(File zipFile, File unZipDir) throws IOException
  {
    unZip(new ZipFile(zipFile), unZipDir);
  }

  private static void unZip(ZipFile zipFile, File unZipDir) throws IOException
  {
    File subFile;
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
    if(!unZipDir.exists()){
      unZipDir.mkdirs();
    }

    while (entries.hasMoreElements())
    {
      ZipEntry zipEntry = entries.nextElement();
      subFile = new File(unZipDir, zipEntry.getName());
      if (zipEntry.isDirectory())
      {
        subFile.mkdirs();
      } else
      {
        unZipSubFile(zipFile, zipEntry, subFile);
      }
    }
  }


  private static void unZipSubFile(ZipFile zipFile, ZipEntry zipEntry, File subFile) throws IOException
  {
    copy(zipFile.getInputStream(zipEntry), new FileOutputStream(subFile));
  }

  /**
   * 拷贝
   *
   * @param inputStream  输入流
   * @param outputStream 输出流
   * @throws IOException 异常
   */
  private static void copy(InputStream inputStream, OutputStream outputStream) throws IOException
  {
    byte[] buffer = new byte[1024];
    int len;
    try (
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        BufferedInputStream bis = new BufferedInputStream(inputStream)
    )
    {
      while ((len = bis.read(buffer)) != -1)
      {
        bos.write(buffer, 0, len);
      }
    }
  }
}
