package cn.reghao.tnb.file.app.service;

import cn.reghao.tnb.common.web.ServletUtil;
import cn.reghao.tnb.content.api.dto.CamPhoto;
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 jakarta.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(String kmlFile, List<CamPhoto> list) throws Exception {
        String template = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n" +
                "<Document>\n" +
                "</Document>\n" +
                "</kml>";
        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 (CamPhoto 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(kmlFile);
        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, CamPhoto camPhoto) {
        String photoUrl = camPhoto.getPhotoUrl();
        String[] arr = photoUrl.split("/");
        String filename = arr[arr.length-1].replace("IMG_", "").replace(".jpg", "");

        String name = filename;
        //String name = camPhoto.getPhotoUrl();
        String lat = camPhoto.getLatitude().toString();
        String lng = camPhoto.getLongitude().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();
    }
}
