package com.example.PhotoGallery.Services;

import java.io.File;
import java.io.IOException;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

import org.json.simple.JSONObject;
import org.springframework.stereotype.Service;

@Service
public class ExtractImageMetadata {

    public JSONObject getImageMetaData(String path) {
        File imageFile = new File(path); 
        try {                                

            Metadata metadata = ImageMetadataReader.readMetadata(imageFile);

            JSONObject metaData = new JSONObject();

            for (Directory directory : metadata.getDirectories()) {
                if (directory.getName().equals("ICC Profile")) {
                    continue;
                }
                JSONObject metadataItem = new JSONObject();

                for (Tag tag : directory.getTags()) {
                    metadataItem.put(tag.getTagName(), tag.getDescription());
                }

                metaData.put(directory.getName(), metadataItem);

            }

            return metaData;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (com.drew.imaging.ImageProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
