package com.lemenzo.gallery.details;

import android.content.Context;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Log;

import com.lemenzo.gallery.model.MediaDetails;

import java.io.InputStream;
import java.util.Locale;

public final class ExifReader {
    private static final String TAG = "LemenzoGalleryExif";

    private ExifReader() {}

    public static MediaDetails read(Context context, Uri uri) {
        MediaDetails details = new MediaDetails();
        try (InputStream input = context.getContentResolver().openInputStream(uri)) {
            if (input == null) return details;
            ExifInterface exif = new ExifInterface(input);
            details.cameraMake = value(exif.getAttribute(ExifInterface.TAG_MAKE));
            details.cameraModel = value(exif.getAttribute(ExifInterface.TAG_MODEL));
            details.lensModel = value(exif.getAttribute("LensModel"));
            details.dateTime = value(exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL));
            details.orientation = value(exif.getAttribute(ExifInterface.TAG_ORIENTATION));
            details.aperture = value(exif.getAttribute(ExifInterface.TAG_F_NUMBER));
            details.exposureTime = value(exif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME));
            details.iso = value(exif.getAttribute(ExifInterface.TAG_ISO_SPEED_RATINGS));
            details.focalLength = value(exif.getAttribute(ExifInterface.TAG_FOCAL_LENGTH));
            float[] latLong = new float[2];
            if (exif.getLatLong(latLong)) {
                details.latitude = String.format(Locale.US, "%.6f", latLong[0]);
                details.longitude = String.format(Locale.US, "%.6f", latLong[1]);
            }
        } catch (Exception exception) {
            Log.d(TAG, "No readable EXIF metadata for " + uri, exception);
        }
        return details;
    }

    private static String value(String value) {
        return value == null ? "" : value;
    }
}
