package com.mxn.helper.screenshot.utils;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {

    private static final int BUFFER_SIZE = 4096;

    public static void zipFolder(String sourceFolderPath, String zipFilePath) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFilePath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            File sourceFolder = new File(sourceFolderPath);
            for (File file : sourceFolder.listFiles()) {
                addFileToZip(zos, file, sourceFolderPath);
            }
            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addFileToZip(ZipOutputStream zos, File file, String sourceFolderPath) throws IOException {
        if (file.isDirectory()) {
            for (File subFile : file.listFiles()) {
                addFileToZip(zos, subFile, sourceFolderPath);
            }
        } else {
            String relativePath = file.getAbsolutePath().substring(sourceFolderPath.length() + 1);
            ZipEntry zipEntry = new ZipEntry(relativePath);
            zos.putNextEntry(zipEntry);
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, len);
            }
            fis.close();
        }
    }
}
