/*
 * Copyright (C) 2006, Jamie McCracken <jamiemcc@gnome.org>
 * Copyright (C) 2008, Nokia <ivan.frade@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

#include "config-miners.h"

#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdint.h>

#include <glib/gstdio.h>

#include <tiffio.h>
#include <tracker-common.h>

#include "utils/tracker-extract.h"

#ifdef HAVE_EXEMPI
#include "tracker-xmp.h"
#endif
#ifdef HAVE_GEXIV2
#include "tracker-exif.h"
#include "tracker-iptc.h"
#endif

#define CMS_PER_INCH        2.54

typedef enum {
	TAG_TYPE_UNDEFINED = 0,
	TAG_TYPE_STRING,
	TAG_TYPE_UINT16,
	TAG_TYPE_UINT32,
	TAG_TYPE_DOUBLE,
	TAG_TYPE_C16_UINT16
} TagType;

typedef struct {
	const gchar *make;
	const gchar *model;
	const gchar *title;
	const gchar *orientation;
	const gchar *copyright;
	const gchar *white_balance;
	const gchar *fnumber;
	const gchar *flash;
	const gchar *focal_length;
	const gchar *artist;
	const gchar *exposure_time;
	const gchar *iso_speed_ratings;
	const gchar *date;
	const gchar *description;
	const gchar *metering_mode;
	const gchar *x_dimension;
	const gchar *y_dimension;
	const gchar *gps_altitude;
	const gchar *gps_latitude;
	const gchar *gps_longitude;
	const gchar *gps_direction;
} MergeData;

typedef struct {
	gchar *artist;
	gchar *copyright;
	gchar *date;
	gchar *title;
	gchar *description;
	gchar *width;
	gchar *length;
	gchar *make;
	gchar *model;
	gchar *orientation;
} TiffData;

static void
tiff_data_free (TiffData *tags)
{
	g_free (tags->artist);
	g_free (tags->copyright);
	g_free (tags->date);
	g_free (tags->title);
	g_free (tags->description);
	g_free (tags->width);
	g_free (tags->length);
	g_free (tags->make);
	g_free (tags->model);
	g_free (tags->orientation);
}

static gchar *
get_flash (TIFF *image)
{
	guint16 data = 0;

	if (TIFFGetField (image, EXIFTAG_FLASH, &data)) {
		switch (data) {
		case 0x0001:
		case 0x0009:
		case 0x000D:
		case 0x000F:
		case 0x0019:
		case 0x001D:
		case 0x001F:
		case 0x0041:
		case 0x0045:
		case 0x0047:
		case 0x0049:
		case 0x004D:
		case 0x004F:
		case 0x0059:
		case 0x005F:
		case 0x005D:
			return g_strdup ("nmm:flash-on");
		default:
			return g_strdup ("nmm:flash-off");
		}
	}

	return NULL;
}

static gchar *
get_orientation (TIFF *image)
{
	guint16 data = 0;

	if (TIFFGetField (image, TIFFTAG_ORIENTATION, &data)) {
		switch (data) {
		case 1: return g_strdup ("nfo:orientation-top");
		case 2:	return g_strdup ("nfo:orientation-top-mirror");
		case 3:	return g_strdup ("nfo:orientation-bottom");
		case 4:	return g_strdup ("nfo:orientation-bottom-mirror");
		case 5:	return g_strdup ("nfo:orientation-left-mirror");
		case 6:	return g_strdup ("nfo:orientation-right");
		case 7:	return g_strdup ("nfo:orientation-right-mirror");
		case 8:	return g_strdup ("nfo:orientation-left");
		}
	}

	return NULL;
}

static gchar *
get_metering_mode (TIFF *image)
{
	guint16 data = 0;

	if (TIFFGetField (image, EXIFTAG_METERINGMODE, &data)) {
		switch (data) {
		case 1: return g_strdup ("nmm:metering-mode-average");
		case 2: return g_strdup ("nmm:metering-mode-center-weighted-average");
		case 3: return g_strdup ("nmm:metering-mode-spot");
		case 4: return g_strdup ("nmm:metering-mode-multispot");
		case 5: return g_strdup ("nmm:metering-mode-pattern");
		case 6: return g_strdup ("nmm:metering-mode-partial");
		default: 
			return g_strdup ("nmm:metering-mode-other");
		}
	}

	return NULL;
}

static gchar *
get_white_balance (TIFF *image)
{
	guint16 data = 0;

	if (TIFFGetField (image, EXIFTAG_WHITEBALANCE, &data)) {
		if (data == 0) {
			return g_strdup ("nmm:white-balance-auto");
		} else {
			return g_strdup ("nmm:white-balance-manual");
		}
	}

	return NULL;
}

static gchar *
tag_to_string (TIFF    *image, 
               guint    tag,
               TagType  type)
{
	switch (type) {
	case TAG_TYPE_STRING: {
		gchar *data = NULL;

		if (TIFFGetField (image, tag, &data)) {
			return g_strdup (data);
		}
		break;
	}

	case TAG_TYPE_UINT16: {
		guint16 data = 0;

		if (TIFFGetField (image, tag, &data)) {
			return g_strdup_printf ("%i", data);
		}
		break;
	}

	case TAG_TYPE_UINT32: {
		guint32 data = 0;

		if (TIFFGetField (image, tag, &data)) {
			return g_strdup_printf ("%i", data);
		}
		break;
	}

	case TAG_TYPE_DOUBLE: {
		gfloat data = 0;

		if (TIFFGetField (image, tag, &data)) {
			return g_strdup_printf ("%f", data);
		}
		break;
	}

	case TAG_TYPE_C16_UINT16: {
		void *data = NULL;
		guint16 count = 0;

		if (TIFFGetField (image, tag, &count, &data)) {
			return g_strdup_printf ("%i", * (guint16*) data);
		}
		break;
	}

	default:
		break;
	}

	return NULL;
}

G_MODULE_EXPORT gboolean
tracker_extract_get_metadata (TrackerExtractInfo  *info,
                              GError             **error)
{
	TrackerResource *metadata;
	TIFF *image;
#ifdef HAVE_EXEMPI
	TrackerXmpData *xd = NULL;
#endif
#ifdef HAVE_GEXIV2
	TrackerIptcData *id = NULL;
#endif
	TrackerExifData *ed = NULL;
	MergeData md = { 0 };
	TiffData td = { 0 };
	g_autofree char *resource_uri = NULL;
	gchar *filename, *uri;
	gchar *date;
	glong exif_offset;
	GFile *file;
	int fd;

#ifdef HAVE_GEXIV2
	gchar *iptc_offset;
	guint32 iptc_size;
#endif

#ifdef HAVE_EXEMPI
	gchar *xmp_offset;
	guint32 size;
#endif /* HAVE_EXEMPI */

	file = tracker_extract_info_get_file (info);
	filename = g_file_get_path (file);

	fd = tracker_file_open_fd (filename);

	if (fd == -1) {
		g_set_error (error,
		             G_IO_ERROR,
		             g_io_error_from_errno (errno),
		             "Could not open tiff file: %s",
		             g_strerror (errno));
		g_free (filename);
		return FALSE;
	}

	if ((image = TIFFFdOpen (fd, filename, "r")) == NULL){
		g_set_error (error,
		             G_IO_ERROR,
		             G_IO_ERROR_INVALID_ARGUMENT,
		             "Could not parse tiff file");
		g_free (filename);
		close (fd);
		return FALSE;
	}

	resource_uri = tracker_extract_info_get_content_id (info, NULL);
	metadata = tracker_resource_new (resource_uri);
	tracker_resource_add_uri (metadata, "rdf:type", "nfo:Image");
	tracker_resource_add_uri (metadata, "rdf:type", "nmm:Photo");

	uri = g_file_get_uri (file);

#ifdef HAVE_GEXIV2
	if (TIFFGetField (image,
	                  TIFFTAG_RICHTIFFIPTC,
	                  &iptc_size,
	                  &iptc_offset)) {
		const TIFFField *field;
		TIFFDataType field_type;

		field = TIFFFieldWithTag (image, TIFFTAG_RICHTIFFIPTC);
		field_type = TIFFFieldDataType (field);

		if (field_type == TIFF_LONG || field_type == TIFF_UNDEFINED) {
			if (field_type == TIFF_LONG) {
				if (TIFFIsByteSwapped (image) != 0) {
					TIFFSwabArrayOfLong ((uint32_t *) iptc_offset,
					                     (unsigned long) iptc_size);
				}

				iptc_size = 4 * iptc_size;
			}

			id = tracker_iptc_new (iptc_offset, iptc_size, uri);
		}
	}

#endif /* HAVE_GEXIV2 */

	/* FIXME There are problems between XMP data embedded with different tools
	   due to bugs in the original spec (type) */
#ifdef HAVE_EXEMPI
	if (TIFFGetField (image, TIFFTAG_XMLPACKET, &size, &xmp_offset)) {
		xd = tracker_xmp_new (xmp_offset, size, uri);
	} else {
		gchar *sidecar = NULL;

		xd = tracker_xmp_new_from_sidecar (file, &sidecar);

		if (sidecar) {
			TrackerResource *sidecar_resource;

			sidecar_resource = tracker_resource_new (sidecar);
			tracker_resource_add_uri (sidecar_resource, "rdf:type", "nfo:FileDataObject");
			tracker_resource_set_uri (sidecar_resource, "nie:interpretedAs", resource_uri);

			tracker_resource_add_take_relation (metadata, "nie:isStoredAs", sidecar_resource);
		}
	}

#endif /* HAVE_EXEMPI */

	ed = g_new0 (TrackerExifData, 1);

	/* Get Tiff specifics */
	td.width = tag_to_string (image, TIFFTAG_IMAGEWIDTH, TAG_TYPE_UINT32);
	td.length = tag_to_string (image, TIFFTAG_IMAGELENGTH, TAG_TYPE_UINT32);
	td.artist = tag_to_string (image, TIFFTAG_ARTIST, TAG_TYPE_STRING);
	td.copyright = tag_to_string (image, TIFFTAG_COPYRIGHT, TAG_TYPE_STRING);

	date = tag_to_string (image, TIFFTAG_DATETIME, TAG_TYPE_STRING);
	td.date = tracker_date_guess (date);
	g_free (date);

	td.title = tag_to_string (image, TIFFTAG_DOCUMENTNAME, TAG_TYPE_STRING);
	td.description = tag_to_string (image, TIFFTAG_IMAGEDESCRIPTION, TAG_TYPE_STRING);
	td.make = tag_to_string (image, TIFFTAG_MAKE, TAG_TYPE_STRING);
	td.model = tag_to_string (image, TIFFTAG_MODEL, TAG_TYPE_STRING);
	td.orientation = get_orientation (image);

	/* Get Exif specifics */
#ifdef HAVE_GEXIV2
	if (TIFFGetField (image, TIFFTAG_EXIFIFD, &exif_offset)) {
		if (TIFFReadEXIFDirectory (image, exif_offset)) {
			ed->exposure_time = tag_to_string (image, EXIFTAG_EXPOSURETIME, TAG_TYPE_DOUBLE);
			ed->fnumber = tag_to_string (image, EXIFTAG_FNUMBER, TAG_TYPE_DOUBLE);
			ed->iso_speed_ratings = tag_to_string (image, EXIFTAG_ISOSPEEDRATINGS, TAG_TYPE_C16_UINT16);
			date = tag_to_string (image, EXIFTAG_DATETIMEORIGINAL, TAG_TYPE_STRING);
			ed->time_original = tracker_date_guess (date);
			g_free (date);

			ed->metering_mode = get_metering_mode (image);
			ed->flash = get_flash (image);
			ed->focal_length = tag_to_string (image, EXIFTAG_FOCALLENGTH, TAG_TYPE_DOUBLE);
			ed->white_balance = get_white_balance (image);
			/* ed->software = tag_to_string (image, EXIFTAG_SOFTWARE, TAG_TYPE_STRING); */
		}
	}
#endif

	TIFFClose (image);
	g_free (filename);

	md.title = tracker_coalesce_strip (2, td.title, ed->document_name);
	md.orientation = tracker_coalesce_strip (2, td.orientation, ed->orientation);
	md.copyright = tracker_coalesce_strip (2, td.copyright, ed->copyright);
	md.white_balance = tracker_coalesce_strip (1, ed->white_balance);
	md.fnumber = tracker_coalesce_strip (1, ed->fnumber);
	md.flash = tracker_coalesce_strip (1, ed->flash);
	md.focal_length = tracker_coalesce_strip (1, ed->focal_length);
	md.artist = tracker_coalesce_strip (2, td.artist, ed->artist);
	md.exposure_time = tracker_coalesce_strip (1, ed->exposure_time);
	md.iso_speed_ratings = tracker_coalesce_strip (1, ed->iso_speed_ratings);
	md.date = tracker_coalesce_strip (3, td.date, ed->time, ed->time_original);
	md.description = tracker_coalesce_strip (2, td.description, ed->description);
	md.metering_mode = tracker_coalesce_strip (1, ed->metering_mode);

	md.gps_altitude = tracker_coalesce_strip (1, ed->gps_altitude);
	md.gps_latitude = tracker_coalesce_strip (1, ed->gps_latitude);
	md.gps_longitude = tracker_coalesce_strip (1, ed->gps_longitude);
	md.gps_direction = tracker_coalesce_strip (1, ed->gps_direction);
	md.x_dimension = tracker_coalesce_strip (2, td.width, ed->x_dimension);
	md.y_dimension = tracker_coalesce_strip (2, td.length, ed->y_dimension);
	md.make = tracker_coalesce_strip (2, td.make, ed->make);
	md.model = tracker_coalesce_strip (2, td.model, ed->model);

	if (ed->user_comment) {
		tracker_guarantee_resource_utf8_string (metadata, "nie:comment", ed->user_comment);
	}

	if (md.x_dimension) {
		tracker_resource_set_string (metadata, "nfo:width", md.x_dimension);
	}

	if (md.y_dimension) {
		tracker_resource_set_string (metadata, "nfo:height", md.y_dimension);
	}

	if (md.gps_altitude || md.gps_latitude || md.gps_longitude) {
		TrackerResource *location;

		location = tracker_extract_new_location (NULL, NULL, NULL, NULL,
		                                         md.gps_altitude, md.gps_latitude,
		                                         md.gps_longitude);

		tracker_resource_set_relation (metadata, "slo:location", location);

		g_object_unref (location);
	}

	if (md.gps_direction) {
		double value;
		value = g_ascii_strtod (md.gps_direction, NULL);
		tracker_resource_set_double (metadata, "nfo:heading", value);
	}

	if (md.make || md.model) {
		TrackerResource *equipment = tracker_extract_new_equipment (md.make, md.model);

		tracker_resource_set_relation (metadata, "nfo:equipment", equipment);

		g_object_unref (equipment);
	}

	tracker_guarantee_resource_title_from_file (metadata,
	                                            "nie:title",
	                                            md.title,
	                                            uri,
	                                            NULL);

	if (md.orientation) {
		TrackerResource *orientation;

		orientation = tracker_resource_new (md.orientation);
		tracker_resource_set_relation (metadata, "nfo:orientation", orientation);
		g_object_unref (orientation);
	}

	if (md.copyright) {
		tracker_guarantee_resource_utf8_string (metadata, "nie:copyright", md.copyright);
	}

	if (md.white_balance) {
		TrackerResource *white_balance;

		white_balance = tracker_resource_new (md.white_balance);
		tracker_resource_set_relation (metadata, "nmm:whiteBalance", white_balance);
		g_object_unref (white_balance);
	}

	if (md.fnumber) {
		tracker_resource_set_string (metadata, "nmm:fnumber", md.fnumber);
	}

	if (md.flash) {
		TrackerResource *flash;

		flash = tracker_resource_new (md.flash);
		tracker_resource_set_relation (metadata, "nmm:flash", flash);
		g_object_unref (flash);
	}

	if (md.focal_length) {
		tracker_resource_set_string (metadata, "nmm:focalLength", md.focal_length);
	}

	if (md.artist) {
		TrackerResource *artist = tracker_extract_new_contact (md.artist);

		tracker_resource_set_relation (metadata, "nco:contributor", artist);

		g_object_unref (artist);
	}

	if (md.exposure_time) {
		tracker_resource_set_string (metadata, "nmm:exposureTime", md.exposure_time);
	}

	if (md.iso_speed_ratings) {
		tracker_resource_set_string (metadata, "nmm:isoSpeed", md.iso_speed_ratings);
	}

	tracker_guarantee_resource_date_from_file_mtime (metadata,
	                                                 "nie:contentCreated",
	                                                 md.date,
	                                                 uri);

	if (md.description) {
		tracker_guarantee_resource_utf8_string (metadata, "nie:description", md.description);
	}

	if (md.metering_mode) {
		TrackerResource *metering;

		metering = tracker_resource_new (md.metering_mode);
		tracker_resource_set_relation (metadata, "nmm:meteringMode", metering);
		g_object_unref (metering);
	}

#ifdef HAVE_GEXIV2
	if (ed->x_resolution) {
		gdouble value;

		if (ed->resolution_unit == EXIF_RESOLUTION_UNIT_PER_CENTIMETER)
			value = g_strtod (ed->x_resolution, NULL) * CMS_PER_INCH;
		else
			value = g_strtod (ed->x_resolution, NULL);

		tracker_resource_set_double (metadata, "nfo:horizontalResolution", value);
	}

	if (ed->y_resolution) {
		gdouble value;

		if (ed->resolution_unit == EXIF_RESOLUTION_UNIT_PER_CENTIMETER)
			value = g_strtod (ed->y_resolution, NULL) * CMS_PER_INCH;
		else
			value = g_strtod (ed->y_resolution, NULL);

		tracker_resource_set_double (metadata, "nfo:verticalResolution", value);
	}
#endif

#ifdef HAVE_EXEMPI
	if (xd) {
		tracker_xmp_apply_to_resource (metadata, xd);
		tracker_xmp_free (xd);
	}
#endif

#ifdef HAVE_GEXIV2
	if (id) {
		tracker_iptc_apply_to_resource (metadata, id);
		tracker_iptc_free (id);
	}
#endif

	tiff_data_free (&td);
	tracker_exif_free (ed);
	g_free (uri);
	close (fd);

	tracker_extract_info_set_resource (info, metadata);
	g_object_unref (metadata);

	return TRUE;
}
