package com.storlead.mail.util;

import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * @program: storlead-saas-platform
 * @description:
 * @author: chenkq
 * @create: 2026-05-18 11:00
 */
@Log4j2
public class FileExtractor {
    public static List<Message> processZipFile(String zipFilePath) {
        List<Message> mimeMessages = new ArrayList<>();
        try {
            File file = new File(zipFilePath);
            try (ZipFile zipFile = new ZipFile(file)) {
                // 遍历压缩包中的每个条目
                zipFile.stream().forEach(entry -> {
                    try {
                        // 使用指定的编码解码文件名
//                        String entryName = new String(entry.getName().getBytes(StandardCharsets.ISO_8859_1), encoding);
                        InputStream inputStream = zipFile.getInputStream(entry);
                        Session session = Session.getDefaultInstance(System.getProperties());
                        MimeMessage mimeMessage = new MimeMessage(session, inputStream);
                        mimeMessages.add(mimeMessage);

                        // 处理文件内容
                    } catch (Exception e) {
                        log.error("processZipFile --- error",e);
                    }
                });
            }
        }catch (Exception e) {
            log.error("processZipFile -- error",e);
        }
        return mimeMessages;
    }

    // 解压 .zip 文件
    public static void extractZip(Path zipFilePath){
        try {
// 创建一个解压的目录
            Path extractDir = Paths.get("extracted_files");
            Files.createDirectories(extractDir);

            // 解压 ZIP 文件
            try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath.toFile()))) {
                ZipEntry entry;
                while ((entry = zipIn.getNextEntry()) != null) {
                    // 读取每个文件条目
                    Path filePath = extractDir.resolve(entry.getName());
                    // 如果条目是目录，创建目录
                    if (entry.isDirectory()) {
                        Files.createDirectories(filePath);
                    } else {
                        // 如果是文件，写入内容
                        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath.toFile()))) {
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = zipIn.read(buffer)) > 0) {
                                bos.write(buffer, 0, length);
                            }
                        }
                    }
                    zipIn.closeEntry();
                }
            }
        }catch (Exception e) {
            log.error("extractZip - error", e);
        }

    }

//    public static List<Message> processZipInMemory(InputStream zipInputStream)  {
//        List<Message> mimeMessages = new ArrayList<>();
//        try {
//            try (ZipInputStream zipIn = new ZipInputStream(zipInputStream)) {
//                ZipEntry entry;
//                while ((entry = zipIn.getNextEntry()) != null) {
//                    // 如果条目是 .eml 文件，进行处理
//                    if (entry.getName().endsWith(".eml")) {
//                        Session session = Session.getDefaultInstance(System.getProperties());
//                        MimeMessage mimeMessage = new MimeMessage(session, zipIn);
//                        mimeMessages.add(mimeMessage);
//                    }
//                    zipIn.closeEntry();
//                }
//            }
//        }catch (Exception e) {
//            log.error("processZipInMemory -- error",e);
//        }
//        return mimeMessages;
//    }

    public static List<Message> processZipInMemory(InputStream zipInputStream) {
        List<Message> mimeMessages = new ArrayList<>();
        try {
            processZipRecursively(zipInputStream, mimeMessages);
        } catch (Exception e) {
            log.error("Error processing ZIP file recursively", e);
        }
        return mimeMessages;
    }

    private static void processZipRecursively(InputStream inputStream, List<Message> mimeMessages) throws Exception {
        ZipInputStream zipIn1 = new ZipInputStream(inputStream, StandardCharsets.ISO_8859_1);
        try (ZipInputStream zipIn = zipIn1) {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {
                try {
                    if (entry.getName().endsWith(".eml")) {
                        // Process EML file
                        Session session = Session.getDefaultInstance(System.getProperties());
                        MimeMessage mimeMessage = new MimeMessage(session, zipIn);
                        mimeMessages.add(mimeMessage);
                    } else if (entry.getName().toLowerCase().endsWith(".zip")) {
                        // Recursively process nested ZIP files
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[8192];
                        int bytesRead;
                        while ((bytesRead = zipIn.read(buffer)) != -1) {
                            baos.write(buffer, 0, bytesRead);
                        }

                        ByteArrayInputStream nestedZipStream = new ByteArrayInputStream(baos.toByteArray());
                        processZipRecursively(nestedZipStream, mimeMessages);
                    }
                } finally {
                    zipIn.closeEntry();
                }
            }
        }
    }
    // 逐条处理解压后的文件
    public static List<Message> processExtractedFiles(Path extractedDir) {
        List<Message> mimeMessages = new ArrayList<>();
        try {
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(extractedDir)) {
                for (Path entry : stream) {
                    // 如果是 .eml 文件，则解析
                    if (entry.toString().endsWith(".eml")) {
                        try (InputStream emlInputStream = Files.newInputStream(entry)) {
                            Session session = Session.getDefaultInstance(System.getProperties());
                            MimeMessage mimeMessage = new MimeMessage(session, emlInputStream);
                            mimeMessages.add(mimeMessage);
                        }
                    } else {
                        System.out.println("Skipping non-email file: " + entry.getFileName());
                    }
                }
            }
        }catch (Exception e) {
            log.error("processExtractedFiles error");
        }
        return mimeMessages;
    }
}
