package com.jsowell.common.util;

import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
    public static File createZipFileFromImages(List<String> imageUrls) {
        if (CollectionUtils.isEmpty(imageUrls)) {
            return null;
        }
        String fileName = "images-" + System.currentTimeMillis() + ".zip";
        File zipFile = new File(fileName);
        try (FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos)) {
            for (int i = 0; i < imageUrls.size(); i++) {
                String imageUrl = imageUrls.get(i);
                URL url = new URL(imageUrl);
                InputStream is = url.openStream();
                ZipEntry zipEntry = new ZipEntry("image" + i + ".jpg");
                zos.putNextEntry(zipEntry);

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    zos.write(buffer, 0, bytesRead);
                }

                is.close();
                zos.closeEntry();
            }
        } catch (IOException ignored) {

        }
        return zipFile;
    }

    public static void main(String[] args) {
        List<String> list = Lists.newArrayList();
        list.add("https://img.jsowellcloud.com/img/2023/06/09/tmp_063ba486f06c7fbf7b7dad64ad06672a_20230609090728A002.jpg");
        list.add("https://img.jsowellcloud.com/img/2023/06/09/tmp_37828a90cc20d4b7fcbc6f62e1d2c729_20230609090658A001.jpg");

        File zipFileFromImages = ZipUtil.createZipFileFromImages(list);
        System.out.println(zipFileFromImages);
    }

    /**
     * 删除指定文件夹下的所有文件
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
        }
        return flag;
    }
}
