/*
 * Metadata through gexiv2: rotating by the EXIF orientation (nothing is
 * decoded and encoded again, so a JPEG loses nothing; glycin turns it
 * when it decodes), and the camera's details for the Details panel.
 */
#include <stdio.h>
#include <string.h>
#include "config.h"
#include "photos.h"
#include "stealth.h"
#if HAVE_GEXIV2
#include <gexiv2/gexiv2.h>
#endif

#if HAVE_GEXIV2
/* Types exiv2 writes EXIF into and glycin reads the orientation from */
static const char *const rotatable[] = {
	"image/jpeg", "image/png", "image/webp", "image/tiff",
};
#endif

bool ph_can_rotate(const char *mime) {
#if HAVE_GEXIV2
	for (size_t i = 0; mime && i < G_N_ELEMENTS(rotatable); i++) {
		if (strcmp(mime, rotatable[i]) == 0) {
			return true;
		}
	}
#endif
	return false;
}

#if HAVE_GEXIV2
/* EXIF orientation after a quarter turn clockwise: the display is the
 * old one turned, and each orientation is a turn and maybe a mirror */
static const int clockwise[9] = { 1, 6, 7, 8, 5, 2, 3, 4, 1 };

struct rotate {
	char *path;
	int turns;
	ph_done_fn done;
	void *data;
	char *error;
};

static void rotate_free(gpointer p) {
	struct rotate *r = p;
	g_free(r->path);
	g_free(r->error);
	g_free(r);
}

static void rotate_thread(GTask *task, gpointer src, gpointer data,
		GCancellable *c) {
	struct rotate *r = data;
	GError *err = NULL;
	GExiv2Metadata *md = gexiv2_metadata_new();
	if (!gexiv2_metadata_open_path(md, r->path, &err)) {
		r->error = g_strdup_printf("Couldn't read the picture: %s",
			err->message);
		goto out;
	}
	int o = gexiv2_metadata_get_orientation(md, NULL);
	if (o < 1 || o > 8) {
		o = 1;
	}
	int turns = ((r->turns % 4) + 4) % 4;
	for (int i = 0; i < turns; i++) {
		o = clockwise[o];
	}
	gexiv2_metadata_set_orientation(md, o, &err);
	if (err == NULL) {
		gexiv2_metadata_save_file(md, r->path, &err);
	}
	if (err) {
		r->error = g_strdup_printf("Couldn't save the turned picture: %s",
			err->message);
	}
out:
	g_clear_error(&err);
	g_object_unref(md);
	g_task_return_boolean(task, TRUE);
}

static void rotated(GObject *src, GAsyncResult *res, gpointer data) {
	struct rotate *r = g_task_get_task_data(G_TASK(res));
	r->done(r->error, r->data);
}
#endif

void ph_rotate(const char *uri, int quarter_turns, ph_done_fn done,
		void *data) {
#if HAVE_GEXIV2
	char *path = g_filename_from_uri(uri, NULL, NULL);
	if (path == NULL) {
		done("Only pictures on this PC can be turned.", data);
		return;
	}
	struct rotate *r = g_new0(struct rotate, 1);
	r->path = path;
	r->turns = quarter_turns;
	r->done = done;
	r->data = data;
	GTask *task = g_task_new(NULL, NULL, rotated, NULL);
	g_task_set_task_data(task, r, rotate_free);
	g_task_run_in_thread(task, rotate_thread);
	g_object_unref(task);
#else
	done("Photos was built without gexiv2, which it turns pictures with.",
		data);
#endif
}

static void add(GPtrArray *pairs, const char *label, char *value) {
	if (value == NULL || value[0] == '\0') {
		g_free(value);
		return;
	}
	g_ptr_array_add(pairs, g_strdup(label));
	g_ptr_array_add(pairs, value);
}

static char *format_time(GDateTime *t) {
	if (t == NULL) {
		return NULL;
	}
	char *s = g_date_time_format(t, "%x  %X");
	g_date_time_unref(t);
	return s;
}

#if HAVE_GEXIV2
static char *tag(GExiv2Metadata *md, const char *name) {
	if (!gexiv2_metadata_has_tag(md, name, NULL)) {
		return NULL;
	}
	char *s = gexiv2_metadata_get_tag_interpreted_string(md, name, NULL);
	if (s) {
		g_strstrip(s);
	}
	return s;
}

/* "2024:06:01 18:22:05", as EXIF writes it */
static GDateTime *exif_time(const char *s) {
	int y, mo, d, h, mi, sec;
	if (s == NULL || sscanf(s, "%d:%d:%d %d:%d:%d", &y, &mo, &d, &h, &mi,
			&sec) != 6) {
		return NULL;
	}
	return g_date_time_new_local(y, mo, d, h, mi, sec);
}

static void camera_details(const char *path, GPtrArray *pairs) {
	GExiv2Metadata *md = gexiv2_metadata_new();
	if (!gexiv2_metadata_open_path(md, path, NULL)) {
		g_object_unref(md);
		return;
	}
	char *taken = tag(md, "Exif.Photo.DateTimeOriginal");
	add(pairs, "Taken", format_time(exif_time(taken)));
	g_free(taken);
	char *make = tag(md, "Exif.Image.Make");
	char *model = tag(md, "Exif.Image.Model");
	/* Models often start with the make already: "Canon Canon EOS" */
	if (make && model && g_str_has_prefix(model, make)) {
		g_clear_pointer(&make, g_free);
	}
	add(pairs, "Camera", make && model ? g_strdup_printf("%s %s", make,
		model) : g_strdup(model ? model : make));
	g_free(make);
	g_free(model);
	add(pairs, "Aperture", tag(md, "Exif.Photo.FNumber"));
	add(pairs, "Exposure", tag(md, "Exif.Photo.ExposureTime"));
	add(pairs, "ISO", tag(md, "Exif.Photo.ISOSpeedRatings"));
	add(pairs, "Focal length", tag(md, "Exif.Photo.FocalLength"));
	add(pairs, "Flash", tag(md, "Exif.Photo.Flash"));
	g_object_unref(md);
}
#endif

void ph_details(const char *uri, GPtrArray *pairs) {
	GFile *file = g_file_new_for_uri(uri);
	GFileInfo *info = g_file_query_info(file,
		G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME ","
		G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
		G_FILE_ATTRIBUTE_STANDARD_SIZE ","
		G_FILE_ATTRIBUTE_TIME_MODIFIED,
		G_FILE_QUERY_INFO_NONE, NULL, NULL);
	if (info) {
		add(pairs, "Name", c8_stealth_text(g_file_info_get_display_name(info)));
		const char *type = g_file_info_get_content_type(info);
		add(pairs, "Type", type ? g_content_type_get_description(type) :
			NULL);
		add(pairs, "Size", g_format_size(g_file_info_get_size(info)));
		add(pairs, "Modified", format_time(
			g_file_info_get_modification_date_time(info)));
		g_object_unref(info);
	}
	GFile *parent = g_file_get_parent(file);
	if (parent) {
		/* Stealth mode: the persona's home, not the login's */
		char *where = g_file_get_parse_name(parent);
		add(pairs, "Folder", c8_stealth_text(where));
		g_free(where);
		g_object_unref(parent);
	}
#if HAVE_GEXIV2
	char *path = g_file_get_path(file);
	if (path) {
		camera_details(path, pairs);
		g_free(path);
	}
#endif
	g_object_unref(file);
}

/* When it was taken, by its EXIF (local time, as cameras keep it), else
 * 0. Blocks: the date scan's thread. */
gint64 ph_taken(const char *path) {
#if HAVE_GEXIV2
	GExiv2Metadata *md = gexiv2_metadata_new();
	gint64 when = 0;
	if (gexiv2_metadata_open_path(md, path, NULL)) {
		char *s = tag(md, "Exif.Photo.DateTimeOriginal");
		if (s == NULL) {
			s = tag(md, "Exif.Image.DateTime");
		}
		GDateTime *t = exif_time(s);
		if (t) {
			when = g_date_time_to_unix(t);
			g_date_time_unref(t);
		}
		g_free(s);
	}
	g_object_unref(md);
	return when;
#else
	return 0;
#endif
}
