package cn.reghao.tnb.content.app.geo.service;

import cn.reghao.jutil.web.ServletUtil;
import cn.reghao.tnb.content.app.geo.model.vo.MapMarker;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

/**
 * GoogleEarth kml 文件
 *
 * @author reghao
 * @date 2023-09-12 11:11:14
 */
@Service
public class EarthService {
    public void getEarthKml(List<MapMarker> list) throws Exception {
        String template = "";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(template.getBytes(StandardCharsets.UTF_8));
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Iterator<Element> iterator = document.getRootElement().elementIterator();
        // 根元素 <Document></Document>
        Element root = iterator.next();
        root.addElement("name").setText("exports");
        Element folder = addFolder(root, "dir1");
        for (MapMarker mapMarker : list) {
            addPlaceMark(folder, mapMarker);
        }

        /*Element folder1 = addFolder(root, "目录2");
        for (MapMarker mapMarker : list.subList(101, 200)) {
            addPlaceMark(folder1, mapMarker);
        }
        Element folder2 = addFolder(root, "目录3");
        for (MapMarker mapMarker : list.subList(201, 300)) {
            addPlaceMark(folder2, mapMarker);
        }*/

        File out = new File("/home/reghao/Downloads/places2.kml");
        OutputStream outputStream = new FileOutputStream(out);
        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(StandardCharsets.UTF_8.name());
        XMLWriter writer = new XMLWriter(outputStream, format);
        writer.setEscapeText(false);
        writer.write(document);
        writer.close();

        /*ByteArrayInputStream bais = new ByteArrayInputStream(outputStream.toByteArray());
        download("GoogleEarth.kml", bais);*/
    }

    private Element addFolder(Element element, String name) {
        Element folder = element.addElement("Folder");
        folder.addElement("name").setText(name);
        folder.addElement("visibility").setText("0");
        // 目录关闭
        folder.addElement("open").setText("0");
        return folder;
    }

    private void addPlaceMark(Element element, MapMarker mapMarker) {
        String name = mapMarker.getTitle();
        String lat = mapMarker.getPosition().getLat().toString();
        String lng = mapMarker.getPosition().getLng().toString();

        Element placeMark = element.addElement("Placemark");
        placeMark.addElement("name").setText(name);
        placeMark.addElement("visibility").setText("0");
        Element point = placeMark.addElement("Point");
        Element coordinates = point.addElement("coordinates");
        // 坐标关闭
        coordinates.setText(lng + " " + lat + ",0");
    }

    public void download(String filename, InputStream in) throws IOException {
        HttpServletResponse response = ServletUtil.getResponse();
        prepareResponse(filename, response);
        download(in, response.getOutputStream());
    }

    private void prepareResponse(String filename, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()));
    }

    private void download(InputStream in, OutputStream out) throws IOException {
        // 1MiB
        byte[] buffer = new byte[1024*1024];
        int i = in.read(buffer);
        while (i != -1) {
            out.write(buffer, 0, i);
            i = in.read(buffer);
        }
        in.close();
        out.close();
    }
}
