package com.multictrl.common.utils.kmz;

import com.multictrl.modules.business.dto.RouteDTO;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * kmz工具类
 *
 * @author Sdy
 * @since 1.0.0 2026/4/21
 */
public class KmzUtils {
    private static final String WPMZ_TEMPLATE_KML = "wpmz/template.kml";
    private static final String WPMZ_WAYLINES_WPML = "wpmz/waylines.wpml";

    /**
     * 生成byte[]数组
     */
    public static byte[] generateKmzBytes(RouteDTO route) throws IOException {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream)) {

            // 添加 wpmz/template.kml 文件
            String kmlContent = TemplateUtils.createTemplateContent(route);
            addEntry(zos, WPMZ_TEMPLATE_KML, kmlContent);

            // 添加 wpmz/waylines.wpl 文件
            String waylinesContent = WaylinesUtils.createTemplateContent(route);
            addEntry(zos, WPMZ_WAYLINES_WPML, waylinesContent);

            zos.finish();
            return byteArrayOutputStream.toByteArray();
        }
    }

    /**
     * 将指定内容写入 ZIP 中指定路径
     */
    private static void addEntry(ZipOutputStream zos, String path, String content) throws IOException {
        zos.putNextEntry(new ZipEntry(path));
        zos.write(content.getBytes(StandardCharsets.UTF_8));
        zos.closeEntry();
    }
}
