package com.inspect.partrolresult.util;

import com.alibaba.fastjson.JSON;
import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.xmp.XmpDirectory;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 解析图片的XMP信息
 */
@Slf4j
public class XmpUtil {
    private static final String DJI_XMP_FLAG = "drone-dji:";
    private static final String[] DJI_XMP_TAGS = {
            "AbsoluteAltitude", "RelativeAltitude", "GpsLongitude", "GpsLatitude",
            "GimbalPitchDegree", "GimbalRollDegree", "GimbalYawDegree",
            "FlightPitchDegree", "FlightRollDegree", "FlightYawDegree"
    };

    /**
     * 解析无人机图片的XMP信息
     * @return 位姿信息JSON字符串
     */
    public static String parseDrone(InputStream inputStream) {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(inputStream);
            Map<String, String> xmpMap = new HashMap<>();
            for (XmpDirectory xmpDir : metadata.getDirectoriesOfType(XmpDirectory.class)) {
                Map<String, String> props = xmpDir.getXmpProperties();
                getDjiTags(xmpMap, props);
            }
            String jsonStr = JSON.toJSONString(xmpMap);
            log.info("Drone XMP info: {}", jsonStr);
            return jsonStr;
        } catch (Exception e) {
            log.error("getXmpInfo error: {}", e.getMessage());
        }
        return "";
    }

    private static void getDjiTags(Map<String, String> xmpMap, Map<String, String> props) {
        for (String tag : DJI_XMP_TAGS) {
            String val = props.get(DJI_XMP_FLAG + tag);
            if (val != null) {
                xmpMap.put(tag, val);
            }
        }
    }
}
