package incheon.ags.dtm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class DtmZipUtil {

    /**
     * 파일 목록을 ZIP 파일로 생성한다.
     *
     * @param zipPath 생성할 zip 파일 전체 경로
     * @param files   압축할 파일 목록 (List<File>)
     */
    public static void create(String zipPath, List<File> files) throws Exception {

        if (files == null || files.isEmpty()) {
            throw new IllegalArgumentException("압축할 파일이 없습니다.");
        }

        File zipFile = new File(zipPath);

        if (zipFile.exists()) {
            zipFile.delete();
        }

        File parentDir = zipFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        byte[] buffer = new byte[4096];

        try (ZipOutputStream zos =
                     new ZipOutputStream(new FileOutputStream(zipFile))) {

            for (File file : files) {

                if (file == null || !file.exists() || !file.isFile()) {
                    continue;
                }

                try (FileInputStream fis = new FileInputStream(file)) {

                    ZipEntry entry = new ZipEntry(file.getName());
                    zos.putNextEntry(entry);

                    int len;
                    while ((len = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }

                    zos.closeEntry();
                }
            }
        }
    }

    /**
     * AS-IS 호환용
     * 파일명 목록 + 파일 경로 목록으로 ZIP 생성
     *
     * @param zipPath    생성할 zip 파일 전체 경로
     * @param filenames 파일명 목록
     * @param filepathes 파일 전체 경로 목록
     */
    public static void create(
            String zipPath,
            List<String> filenames,
            List<String> filepathes) throws Exception {

        if (filenames == null || filepathes == null
                || filenames.isEmpty()
                || filenames.size() != filepathes.size()) {
            throw new IllegalArgumentException("파일 목록 정보가 올바르지 않습니다.");
        }

        List<File> files = new ArrayList<>();

        for (String path : filepathes) {
            File f = new File(path);
            if (f.exists() && f.isFile()) {
                files.add(f);
            }
        }

        create(zipPath, files);
    }
}
