/*
 * Copyright (C) 2004 John Ellis
 * Copyright (C) 2008 - 2016 The Geeqie Team
 *
 * Author: Colin Clark
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "bar-gps.h"

#include <algorithm>
#include <string>
#include <vector>

#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gdk/gdk.h>
#include <gtk/gtk.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <shumate/shumate.h>
#ifdef __cplusplus
}
#endif

#include <config.h>

#include "bar.h"
#include "compat.h"
#include "dnd.h"
#include "filedata.h"
#include "intl.h"
#include "layout.h"
#include "main-defines.h"
#include "metadata.h"
#include "misc.h"
#include "rcfile.h"
#include "thumb.h"
#include "ui-menu.h"
#include "ui-utildlg.h"
#include "uri-utils.h"

namespace
{

constexpr gint DEFAULT_ZOOM = 7;
constexpr gint GPS_MARKER_DIRECTION_SIZE = 36;
constexpr gint GPS_MARKER_THUMB_SIZE = 128;
constexpr const gchar *DEFAULT_MAP_ID = SHUMATE_MAP_SOURCE_OSM_MAPNIK;
constexpr const gchar *DEFAULT_MAP_NAME = "OpenStreetMap";
constexpr const gchar *DEFAULT_MAP_LICENSE = "OpenStreetMap contributors";
constexpr const gchar *DEFAULT_MAP_LICENSE_URI = "https://www.openstreetmap.org/copyright";
constexpr const gchar *DEFAULT_MAP_URL = "https://tile.openstreetmap.org/{z}/{x}/{y}.png";

/*
 *-------------------------------------------------------------------
 * GPS Map utils
 *-------------------------------------------------------------------
 */

struct PaneGPSData
{
	PaneData pane;
	GtkWidget *widget;
	gchar *map_source;
	ShumateMapSource *shumate_map_source;
	gint height;
	FileData *fd;
	ShumateSimpleMap *map;
	ShumateMarkerLayer *marker_layer;
	ShumateViewport *viewport;
	GtkWidget *map_popover_parent;
	GList *selection_list;
	GList *not_added;
	guint num_added;
	guint create_markers_id;
	GList *geocode_list;
	GtkWidget *progress;
	gint selection_count;
	gboolean centre_map_checked;
	gboolean enable_markers_checked;
	gdouble dest_latitude;
	gdouble dest_longitude;
};

struct PaneGPSDndDropData
{
	GtkWidget *widget;
};

struct GPSMarkerData
{
	FileData *fd;
	GtkWidget *summary;
	GtkWidget *details;
	GtkWidget *picture;
	ThumbLoader *thumb_loader;
	gdouble direction;
	gboolean expanded;
};

constexpr const gchar *GPS_MARKER_DATA_KEY = "geeqie-gps-marker-data";

PaneGPSData *bar_pane_gps_dnd_drop_data_get_pane(PaneGPSDndDropData *drop_data)
{
	return static_cast<PaneGPSData *>(g_object_get_data(G_OBJECT(drop_data->widget), "pane_data"));
}

void bar_pane_gps_dnd_drop_data_free(PaneGPSDndDropData *drop_data)
{
	g_object_unref(drop_data->widget);
	g_free(drop_data);
}

/*
 *-------------------------------------------------------------------
 * drag-and-drop
 *-------------------------------------------------------------------
 */

void bar_pane_gps_close_cancel_cb(GenericDialog *, gpointer data)
{
	auto *pgd = static_cast<PaneGPSData *>(data);

	file_data_list_free(pgd->geocode_list);
	pgd->geocode_list = nullptr;
}

void bar_pane_gps_close_save_cb(GenericDialog *, gpointer data)
{
	auto *pgd = static_cast<PaneGPSData *>(data);

	for (GList *work = g_list_first(pgd->geocode_list); work; work = work->next)
		{
		auto *fd = static_cast<FileData *>(work->data);
		if (fd->name && !fd->parent)
			{
			metadata_write_GPS_coord(fd, "Xmp.exif.GPSLatitude", pgd->dest_latitude);
			metadata_write_GPS_coord(fd, "Xmp.exif.GPSLongitude", pgd->dest_longitude);
			}
		}

	file_data_list_free(pgd->geocode_list);
	pgd->geocode_list = nullptr;
}

void bar_pane_gps_dnd_file_received(GdkDrop *drop, GList *list, gpointer data)
{
	auto *drop_data = static_cast<PaneGPSDndDropData *>(data);
	auto *pgd = bar_pane_gps_dnd_drop_data_get_pane(drop_data);
	if (!pgd)
		{
		gdk_drop_finish(drop, GDK_ACTION_NONE);
		bar_pane_gps_dnd_drop_data_free(drop_data);
		return;
		}

	auto action = GDK_ACTION_NONE;

	gint count = 0;
	gint geocoded_count = 0;

	file_data_list_free(pgd->geocode_list);
	pgd->geocode_list = nullptr;

	for (GList *work = list; work; work = work->next)
		{
		auto *fd = static_cast<FileData *>(work->data);
		if (fd->name && !fd->parent)
			{
			count++;
			pgd->geocode_list = g_list_append(pgd->geocode_list, file_data_ref(fd));
			gdouble latitude = metadata_read_GPS_coord(fd, "Xmp.exif.GPSLatitude", 1000);
			gdouble longitude = metadata_read_GPS_coord(fd, "Xmp.exif.GPSLongitude", 1000);
			if (latitude != 1000 && longitude != 1000)
				{
				geocoded_count++;
				}
			}
		}

	if (count)
		{
		g_autoptr(GString) message = g_string_new("");
		if (count == 1)
			{
			auto *fd_found = static_cast<FileData *>(g_list_first(pgd->geocode_list)->data);
			g_string_append_printf(message, _("\nDo you want to geocode image %s?"), fd_found->name);
			}
		else
			{
			g_string_append_printf(message, _("\nDo you want to geocode %i images?"), count);
			}

		if (geocoded_count == 1 && count == 1)
			{
			g_string_append(message, _("\nThis image is already geocoded!"));
			}
		else if (geocoded_count == 1 && count > 1)
			{
			g_string_append(message, _("\nOne image is already geocoded!"));
			}
		else if (geocoded_count > 1 && count > 1)
			{
			g_string_append_printf(message, _("\n%i Images are already geocoded!"), geocoded_count);
			}

		g_string_append_printf(message, _("\n\nPosition: %lf %lf \n"), pgd->dest_latitude, pgd->dest_longitude);

		GenericDialog *gd = generic_dialog_new(_("Geocode images"), "geocode_images", nullptr, TRUE, bar_pane_gps_close_cancel_cb, pgd);
		generic_dialog_add_message(gd, GQ_ICON_DIALOG_QUESTION, _("Write lat/long to meta-data?"), message->str, TRUE);
		generic_dialog_add_button(gd, GQ_ICON_SAVE, _("Save"), bar_pane_gps_close_save_cb, TRUE);

		gtk_widget_show(gd->dialog);
		action = GDK_ACTION_COPY;
		}

	gdk_drop_finish(drop, action);
	bar_pane_gps_dnd_drop_data_free(drop_data);
}

void bar_pane_gps_dnd_text_received(GdkDrop *drop, const gchar *text, gpointer data)
{
	auto *drop_data = static_cast<PaneGPSDndDropData *>(data);
	auto *pgd = bar_pane_gps_dnd_drop_data_get_pane(drop_data);
	if (!pgd)
		{
		gdk_drop_finish(drop, GDK_ACTION_NONE);
		bar_pane_gps_dnd_drop_data_free(drop_data);
		return;
		}

	auto action = GDK_ACTION_NONE;

	if (text)
		{
		g_autofree gchar *location = decode_geo_parameters(text);
		if (location && !g_strstr_len(location, -1, "Error"))
			{
			g_auto(GStrv) latlong = g_strsplit(location, " ", 2);
			if (latlong[0] && latlong[1])
				{
				shumate_map_center_on(shumate_simple_map_get_map(pgd->map),
				                      g_ascii_strtod(latlong[0], nullptr),
				                      g_ascii_strtod(latlong[1], nullptr));
				action = GDK_ACTION_COPY;
				}
			}
		}

	gdk_drop_finish(drop, action);
	bar_pane_gps_dnd_drop_data_free(drop_data);
}

gboolean bar_pane_gps_dnd_drop(GtkDropTargetAsync *target, GdkDrop *drop, gdouble x, gdouble y, gpointer data)
{
	auto *pgd = static_cast<PaneGPSData *>(data);
	GtkWidget *widget = gtk_event_controller_get_widget(GTK_EVENT_CONTROLLER(target));

	GdkContentFormats *formats = gdk_drop_get_formats(drop);
	if (gdk_content_formats_contain_gtype(formats, GDK_TYPE_FILE_LIST) ||
	    gdk_content_formats_contain_mime_type(formats, "text/uri-list"))
		{
		shumate_viewport_widget_coords_to_location(pgd->viewport, widget, x, y, &pgd->dest_latitude, &pgd->dest_longitude);
		auto *drop_data = g_new(PaneGPSDndDropData, 1);
		drop_data->widget = GTK_WIDGET(g_object_ref(pgd->widget));
		dnd_read_file_list_async(drop, bar_pane_gps_dnd_file_received, drop_data);
		return TRUE;
		}

	if (gdk_content_formats_contain_mime_type(formats, "text/plain"))
		{
		auto *drop_data = g_new(PaneGPSDndDropData, 1);
		drop_data->widget = GTK_WIDGET(g_object_ref(pgd->widget));
		dnd_read_text_async(drop, bar_pane_gps_dnd_text_received, drop_data);
		return TRUE;
		}

	return FALSE;
}

void bar_pane_gps_dnd_init(gpointer data)
{
	auto *pgd = static_cast<PaneGPSData *>(data);

	GdkContentFormats *formats = dnd_file_drop_formats(TRUE);
	GtkDropTargetAsync *drop_target = gtk_drop_target_async_new(formats, static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE));
	g_signal_connect(drop_target, "drop", G_CALLBACK(bar_pane_gps_dnd_drop), pgd);
	gtk_widget_add_controller(pgd->widget, GTK_EVENT_CONTROLLER(drop_target));
}

void bar_pane_gps_widget_destroy_cb(GtkWidget *widget, gpointer)
{
	g_object_set_data(G_OBJECT(widget), "pane_data", nullptr);
}

void gps_marker_set_pixbuf(GPSMarkerData *marker_data, GdkPixbuf *pixbuf)
{
	if (!pixbuf) return;

	g_autoptr(GdkTexture) texture = gdk_texture_new_for_pixbuf(pixbuf);
	gtk_picture_set_paintable(GTK_PICTURE(marker_data->picture), GDK_PAINTABLE(texture));
}

void gps_marker_thumb_done_cb(ThumbLoader *thumb_loader, gpointer data)
{
	auto *marker_data = static_cast<GPSMarkerData *>(data);
	g_autoptr(GdkPixbuf) pixbuf = thumb_loader_get_pixbuf(thumb_loader);

	gps_marker_set_pixbuf(marker_data, pixbuf);
	thumb_loader_free(thumb_loader);
	marker_data->thumb_loader = nullptr;
}

void gps_marker_thumb_error_cb(ThumbLoader *thumb_loader, gpointer data)
{
	auto *marker_data = static_cast<GPSMarkerData *>(data);

	thumb_loader_free(thumb_loader);
	marker_data->thumb_loader = nullptr;
}

void gps_marker_ensure_thumbnail(GPSMarkerData *marker_data)
{
	if (gtk_picture_get_paintable(GTK_PICTURE(marker_data->picture)) || marker_data->thumb_loader) return;

	if (marker_data->fd->thumb_pixbuf)
		{
		gps_marker_set_pixbuf(marker_data, marker_data->fd->thumb_pixbuf);
		return;
		}

	marker_data->thumb_loader = thumb_loader_new(GPS_MARKER_THUMB_SIZE, GPS_MARKER_THUMB_SIZE);
	thumb_loader_set_callbacks(marker_data->thumb_loader,
	                           gps_marker_thumb_done_cb,
	                           gps_marker_thumb_error_cb,
	                           nullptr,
	                           marker_data);

	if (!thumb_loader_start(marker_data->thumb_loader, marker_data->fd))
		{
		thumb_loader_free(marker_data->thumb_loader);
		marker_data->thumb_loader = nullptr;
		}
}

void gps_marker_direction_draw_cb(GtkDrawingArea *drawing_area, cairo_t *cr, gint width, gint height, gpointer data)
{
	auto *marker_data = static_cast<GPSMarkerData *>(data);
	GdkRGBA color;
	gtk_widget_get_color(GTK_WIDGET(drawing_area), &color);

	cairo_save(cr);
	cairo_translate(cr, width / 2.0, height / 2.0);
	cairo_rotate(cr, marker_data->direction * G_PI / 180.0);
	cairo_set_source_rgba(cr, color.red, color.green, color.blue, color.alpha);
	cairo_set_line_width(cr, 2.0);
	cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
	cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);

	const gdouble arrow_length = MIN(width, height) * 0.35;
	const gdouble arrow_head = arrow_length * 0.35;

	cairo_move_to(cr, 0, arrow_length);
	cairo_line_to(cr, 0, -arrow_length);
	cairo_line_to(cr, -arrow_head, -arrow_length + arrow_head);
	cairo_move_to(cr, 0, -arrow_length);
	cairo_line_to(cr, arrow_head, -arrow_length + arrow_head);
	cairo_stroke(cr);
	cairo_restore(cr);
}

GtkWidget *gps_marker_details_new(GPSMarkerData *marker_data)
{
	GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
	gtk_widget_add_css_class(box, "gps-marker-details");

	marker_data->picture = gtk_picture_new();
	gtk_picture_set_content_fit(GTK_PICTURE(marker_data->picture), GTK_CONTENT_FIT_CONTAIN);
	gtk_widget_set_size_request(marker_data->picture, GPS_MARKER_THUMB_SIZE, GPS_MARKER_THUMB_SIZE);
	gtk_box_append(GTK_BOX(box), marker_data->picture);

	GtkWidget *name = gtk_label_new(marker_data->fd->name);
	gtk_label_set_ellipsize(GTK_LABEL(name), PANGO_ELLIPSIZE_MIDDLE);
	gtk_label_set_max_width_chars(GTK_LABEL(name), 24);
	gtk_box_append(GTK_BOX(box), name);

	GtkWidget *date = gtk_label_new(text_from_time(marker_data->fd->date));
	gtk_box_append(GTK_BOX(box), date);

	g_autofree gchar *altitude = metadata_read_string(marker_data->fd, "formatted.GPSAltitude", METADATA_FORMATTED);
	if (altitude)
		{
		gtk_box_append(GTK_BOX(box), gtk_label_new(altitude));
		}

	marker_data->direction = metadata_read_GPS_direction(marker_data->fd, "Xmp.exif.GPSImgDirection", 1000);
	if (marker_data->direction != 1000)
		{
		GtkWidget *direction = gtk_drawing_area_new();
		gtk_widget_set_size_request(direction, GPS_MARKER_DIRECTION_SIZE, GPS_MARKER_DIRECTION_SIZE);
		gtk_widget_set_halign(direction, GTK_ALIGN_CENTER);
		gtk_drawing_area_set_draw_func(GTK_DRAWING_AREA(direction), gps_marker_direction_draw_cb, marker_data, nullptr);

		g_autofree gchar *tooltip = g_strdup_printf(_("Image direction: %.1f°"), marker_data->direction);
		gtk_widget_set_tooltip_text(direction, tooltip);
		gtk_box_append(GTK_BOX(box), direction);
		}

	return box;
}

void gps_marker_click_cb(GtkGestureClick *, gint, gdouble, gdouble, gpointer data)
{
	auto *marker = SHUMATE_MARKER(data);
	auto *marker_data = static_cast<GPSMarkerData *>(g_object_get_data(G_OBJECT(marker), GPS_MARKER_DATA_KEY));
	if (!marker_data) return;

	marker_data->expanded = !marker_data->expanded;
	gtk_widget_set_visible(marker_data->summary, !marker_data->expanded);
	gtk_widget_set_visible(marker_data->details, marker_data->expanded);

	if (marker_data->expanded)
		{
		gps_marker_ensure_thumbnail(marker_data);
		}
}

void gps_marker_data_free(gpointer data)
{
	auto *marker_data = static_cast<GPSMarkerData *>(data);

	if (marker_data->thumb_loader)
		{
		thumb_loader_free(marker_data->thumb_loader);
		}

	file_data_unref(marker_data->fd);
	g_free(marker_data);
}

void bar_pane_gps_add_marker(PaneGPSData *pgd, FileData *fd, gdouble latitude, gdouble longitude)
{
	ShumateMarker *marker = shumate_marker_new();
	auto *marker_data = g_new0(GPSMarkerData, 1);
	marker_data->fd = file_data_ref(fd);

	GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 2);
	gtk_widget_add_css_class(box, "gps-marker");

	marker_data->summary = gtk_image_new_from_icon_name("mark-location-symbolic");
	gtk_image_set_pixel_size(GTK_IMAGE(marker_data->summary), 24);
	gtk_widget_add_css_class(marker_data->summary, "gps-marker-summary");
	gtk_box_append(GTK_BOX(box), marker_data->summary);

	marker_data->details = gps_marker_details_new(marker_data);
	gtk_widget_set_visible(marker_data->details, FALSE);
	gtk_box_append(GTK_BOX(box), marker_data->details);

	shumate_marker_set_child(marker, box);
	shumate_marker_set_selectable(marker, TRUE);
	shumate_location_set_location(SHUMATE_LOCATION(marker), latitude, longitude);
	g_object_set_data_full(G_OBJECT(marker), GPS_MARKER_DATA_KEY, marker_data, gps_marker_data_free);

	GtkGesture *click = gtk_gesture_click_new();
	gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(click), GDK_BUTTON_PRIMARY);
	g_signal_connect(click, "released", G_CALLBACK(gps_marker_click_cb), marker);
	gtk_widget_add_controller(GTK_WIDGET(marker), GTK_EVENT_CONTROLLER(click));

	gtk_widget_set_tooltip_text(GTK_WIDGET(marker), fd->name);
	shumate_marker_layer_add_marker(pgd->marker_layer, marker);
}

gboolean bar_pane_gps_add_file_marker(PaneGPSData *pgd, FileData *fd)
{
	if (!pgd || !fd) return FALSE;

	const double lat = metadata_read_GPS_coord(fd, "Xmp.exif.GPSLatitude", 1000);
	const double lon = metadata_read_GPS_coord(fd, "Xmp.exif.GPSLongitude", 1000);

	if (lat == 1000 || lon == 1000)
		{
		return FALSE;
		}

	bar_pane_gps_add_marker(pgd, fd, lat, lon);
	pgd->num_added++;
	if (pgd->centre_map_checked && pgd->selection_count == 1)
		{
		shumate_map_center_on(shumate_simple_map_get_map(pgd->map), lat, lon);
		}

	return TRUE;
}

void bar_pane_gps_fit_markers(PaneGPSData *pgd)
{
	if (!pgd || !pgd->centre_map_checked || pgd->num_added < 2 || !pgd->shumate_map_source) return;

	double min_latitude = 90.0;
	double max_latitude = -90.0;
	std::vector<double> longitudes;

	for (GList *work = pgd->selection_list; work; work = work->next)
		{
		auto *fd = static_cast<FileData *>(work->data);
		const double latitude = metadata_read_GPS_coord(fd, "Xmp.exif.GPSLatitude", 1000);
		const double longitude = metadata_read_GPS_coord(fd, "Xmp.exif.GPSLongitude", 1000);
		if (latitude == 1000 || longitude == 1000) continue;

		min_latitude = MIN(min_latitude, latitude);
		max_latitude = MAX(max_latitude, latitude);
		longitudes.push_back(longitude < 0.0 ? longitude + 360.0 : longitude);
		}

	if (longitudes.size() < 2) return;

	std::sort(longitudes.begin(), longitudes.end());
	double largest_gap = -1.0;
	size_t interval_start = 0;
	for (size_t i = 0; i < longitudes.size(); i++)
		{
		const double next = i + 1 < longitudes.size() ? longitudes[i + 1] : longitudes[0] + 360.0;
		const double gap = next - longitudes[i];
		if (gap > largest_gap)
			{
			largest_gap = gap;
			interval_start = (i + 1) % longitudes.size();
			}
		}

	const double longitude_span = 360.0 - largest_gap;
	double centre_longitude = longitudes[interval_start] + (longitude_span / 2.0);
	if (centre_longitude >= 360.0) centre_longitude -= 360.0;
	if (centre_longitude > 180.0) centre_longitude -= 360.0;

	const gint available_width = MAX(1, gtk_widget_get_width(GTK_WIDGET(pgd->map)) - 64);
	const gint available_height = MAX(1, gtk_widget_get_height(GTK_WIDGET(pgd->map)) - 64);
	const guint min_zoom = shumate_viewport_get_min_zoom_level(pgd->viewport);
	const guint max_zoom = shumate_viewport_get_max_zoom_level(pgd->viewport);
	double zoom = min_zoom;
	double centre_latitude = (min_latitude + max_latitude) / 2.0;

	for (gint candidate = static_cast<gint>(max_zoom); candidate >= static_cast<gint>(min_zoom); candidate--)
		{
		const double tile_size = shumate_map_source_get_tile_size_at_zoom(pgd->shumate_map_source, candidate);
		const double map_width = shumate_map_source_get_column_count(pgd->shumate_map_source, candidate) * tile_size;
		const double longitude_pixels = longitude_span / 360.0 * map_width;
		const double min_y = shumate_map_source_get_y(pgd->shumate_map_source, candidate, min_latitude);
		const double max_y = shumate_map_source_get_y(pgd->shumate_map_source, candidate, max_latitude);
		const double latitude_pixels = ABS(max_y - min_y);

		if (longitude_pixels <= available_width && latitude_pixels <= available_height)
			{
			zoom = candidate;
			centre_latitude = shumate_map_source_get_latitude(pgd->shumate_map_source, candidate, (min_y + max_y) / 2.0);
			break;
			}
		}

	shumate_map_go_to_full(shumate_simple_map_get_map(pgd->map), centre_latitude, centre_longitude, zoom);
}

void bar_pane_gps_set_status(PaneGPSData *pgd)
{
	if (!pgd->viewport) return;
}

void bar_pane_gps_clear_marker_queue(PaneGPSData *pgd)
{
	g_list_free(pgd->not_added);
	pgd->not_added = nullptr;
}

gboolean bar_pane_gps_create_markers_cb(gpointer data)
{
	auto *pgd = static_cast<PaneGPSData *>(data);

	if (!pgd || !pgd->not_added)
		{
		if (pgd)
			{
			gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(pgd->progress), 0);
			gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pgd->progress), nullptr);
			pgd->create_markers_id = 0;
			}
		return G_SOURCE_REMOVE;
		}

	const gint selection_added = pgd->selection_count - g_list_length(pgd->not_added);
	if (pgd->selection_count > 0)
		{
		gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(pgd->progress), static_cast<gdouble>(selection_added) / static_cast<gdouble>(pgd->selection_count));
		}
	g_autofree gchar *message = g_strdup_printf("%u/%i", selection_added, pgd->selection_count);
	gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pgd->progress), message);

	GList *work = pgd->not_added;
	auto *fd = static_cast<FileData *>(work->data);
	pgd->not_added = work->next;
	g_list_free_1(work);

	bar_pane_gps_add_file_marker(pgd, fd);

	bar_pane_gps_set_status(pgd);

	if (pgd->not_added)
		{
		pgd->create_markers_id = g_idle_add(bar_pane_gps_create_markers_cb, pgd);
		}
	else
		{
		gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(pgd->progress), 0);
		gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pgd->progress), nullptr);
		bar_pane_gps_clear_marker_queue(pgd);
		pgd->create_markers_id = 0;
		bar_pane_gps_fit_markers(pgd);
		}

	return G_SOURCE_REMOVE;
}

void bar_pane_gps_update(PaneGPSData *pgd)
{
	if (!pgd) return;

	if (pgd->create_markers_id != 0)
		{
		g_source_remove(pgd->create_markers_id);
		pgd->create_markers_id = 0;
		}

	bar_pane_gps_clear_marker_queue(pgd);
	file_data_list_free(pgd->selection_list);
	pgd->selection_list = layout_selection_list(pgd->pane.lw);
	if (!pgd->selection_list && pgd->fd)
		{
		pgd->selection_list = g_list_append(nullptr, file_data_ref(pgd->fd));
		}
	pgd->selection_list = file_data_process_groups_in_selection(pgd->selection_list, FALSE, nullptr);
	pgd->selection_count = g_list_length(pgd->selection_list);
	pgd->num_added = 0;

	shumate_marker_layer_remove_all(pgd->marker_layer);
	if (!pgd->enable_markers_checked)
		{
		return;
		}

	bar_pane_gps_set_status(pgd);

	if (pgd->selection_list)
		{
		if (pgd->selection_count == 1)
			{
			auto *fd = static_cast<FileData *>(pgd->selection_list->data);
			bar_pane_gps_add_file_marker(pgd, fd);
			}
		else
			{
			pgd->not_added = g_list_copy(pgd->selection_list);
			pgd->create_markers_id = g_idle_add(bar_pane_gps_create_markers_cb, pgd);
			}
		}
}

void bar_pane_gps_set_map_source(PaneGPSData *pgd, const gchar *map_id)
{
	if (!map_id || !*map_id) map_id = DEFAULT_MAP_ID;
	if (g_strcmp0(pgd->map_source, map_id) == 0) return;

	ShumateMapSource *source = nullptr;
	g_autoptr(ShumateMapSourceRegistry) registry = shumate_map_source_registry_new_with_defaults();

	if (g_strcmp0(map_id, DEFAULT_MAP_ID) == 0)
		{
		source = SHUMATE_MAP_SOURCE(shumate_raster_renderer_new_full_from_url(DEFAULT_MAP_ID,
		                                                                      DEFAULT_MAP_NAME,
		                                                                      DEFAULT_MAP_LICENSE,
		                                                                      DEFAULT_MAP_LICENSE_URI,
		                                                                      0,
		                                                                      19,
		                                                                      256,
		                                                                      SHUMATE_MAP_PROJECTION_MERCATOR,
		                                                                      DEFAULT_MAP_URL));
		}

	if (!source)
		{
		source = shumate_map_source_registry_get_by_id(registry, map_id);
		if (source) g_object_ref(source);
		}

	if (source)
		{
		shumate_simple_map_set_map_source(pgd->map, source);
		shumate_viewport_set_reference_map_source(pgd->viewport, source);
		g_clear_object(&pgd->shumate_map_source);
		pgd->shumate_map_source = source;
		g_free(pgd->map_source);
		pgd->map_source = g_strdup(map_id);
		}
}

void bar_pane_gps_enable_markers_checked_toggle_cb(GtkWidget *button, gpointer data)
{
	auto pgd = static_cast<PaneGPSData *>(data);

	pgd->enable_markers_checked = gtk_check_button_get_active(GTK_CHECK_BUTTON(button));
	bar_pane_gps_update(pgd);
}

void bar_pane_gps_centre_map_checked_toggle_cb(GtkWidget *button, gpointer data)
{
	auto pgd = static_cast<PaneGPSData *>(data);

	pgd->centre_map_checked = gtk_check_button_get_active(GTK_CHECK_BUTTON(button));
	bar_pane_gps_fit_markers(pgd);
}

void bar_pane_gps_notify_selection(GtkWidget *bar, gint count)
{
	(void)count;
	PaneGPSData *pgd;

	pgd = static_cast<PaneGPSData *>(g_object_get_data(G_OBJECT(bar), "pane_data"));
	if (!pgd) return;

	bar_pane_gps_update(pgd);
}

void bar_pane_gps_set_fd(GtkWidget *bar, FileData *fd)
{
	PaneGPSData *pgd;

	pgd = static_cast<PaneGPSData *>(g_object_get_data(G_OBJECT(bar), "pane_data"));
	if (!pgd) return;

	file_data_unref(pgd->fd);
	pgd->fd = file_data_ref(fd);

	bar_pane_gps_update(pgd);
}

gint bar_pane_gps_event(GtkWidget *bar, GdkEvent *event)
{
	(void)bar;
	(void)event;
	return FALSE;
}

const gchar *bar_pane_gps_get_map_id(const PaneGPSData *pgd)
{
	return pgd->map_source ? pgd->map_source : DEFAULT_MAP_ID;
}

void bar_pane_gps_write_config(GtkWidget *pane, GString *outstr, gint indent)
{
	auto *pgd = static_cast<PaneGPSData *>(g_object_get_data(G_OBJECT(pane), "pane_data"));
	if (!pgd) return;

	WRITE_NL();
	WRITE_STRING("<pane_gps ");
	WRITE_CHAR(pgd->pane, id);
	WRITE_CHAR_FULL("title", gtk_label_get_text(GTK_LABEL(pgd->pane.title)));
	WRITE_BOOL(pgd->pane, expanded);

	gint w;
	gtk_widget_get_size_request(pane, &w, &pgd->height);
	WRITE_INT(*pgd, height);
	indent++;

	const gchar *map_id = bar_pane_gps_get_map_id(pgd);
	WRITE_NL();
	WRITE_CHAR_FULL("map-id", map_id);

	gdouble zoom = DEFAULT_ZOOM;
	g_object_get(pgd->viewport, "zoom-level", &zoom, NULL);
	WRITE_NL();
	WRITE_INT_FULL("zoom-level", static_cast<gint>(zoom));

	const auto write_lat_long_option = [pgd, outstr, indent](const gchar *option)
	{
		gdouble position = g_strcmp0(option, "latitude") == 0
		                    ? shumate_location_get_latitude(SHUMATE_LOCATION(pgd->viewport))
		                    : shumate_location_get_longitude(SHUMATE_LOCATION(pgd->viewport));
		const gint int_position = position * 1000000;
		WRITE_NL();
		WRITE_INT_FULL(option, int_position);
	};
	write_lat_long_option("latitude");
	write_lat_long_option("longitude");

	indent--;
	WRITE_NL();
	WRITE_STRING("/>");
}

void bar_pane_gps_notify_cb(FileData *fd, NotifyType type, gpointer data)
{
	auto pgd = static_cast<PaneGPSData *>(data);

	if ((type & (NOTIFY_REREAD | NOTIFY_CHANGE | NOTIFY_METADATA)) &&
	    g_list_find(pgd->selection_list, fd))
		{
		bar_pane_gps_update(pgd);
		}
}

GtkWidget *bar_pane_gps_menu(PaneGPSData *pgd)
{
	GtkWidget *popover;
	GtkWidget *menu_box;
	GtkWidget *map_centre;

	popover = gtk_popover_new();
	popover_set_parent(popover, pgd->map_popover_parent);
	menu_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
	gtk_popover_set_child(GTK_POPOVER(popover), menu_box);

	GtkWidget *enable_markers = gtk_check_button_new_with_label(_("Enable markers"));
	gtk_check_button_set_active(GTK_CHECK_BUTTON(enable_markers), pgd->enable_markers_checked);
	g_signal_connect(enable_markers, "toggled", G_CALLBACK(bar_pane_gps_enable_markers_checked_toggle_cb), pgd);
	gtk_box_append(GTK_BOX(menu_box), enable_markers);

	map_centre = gtk_check_button_new_with_label(_("Centre map on marker"));
	gtk_check_button_set_active(GTK_CHECK_BUTTON(map_centre), pgd->centre_map_checked);
	g_signal_connect(map_centre, "toggled", G_CALLBACK(bar_pane_gps_centre_map_checked_toggle_cb), pgd);
	gtk_box_append(GTK_BOX(menu_box), map_centre);
	gtk_widget_set_sensitive(map_centre, pgd->enable_markers_checked);

	return popover;
}

void bar_pane_gps_destroy(gpointer data)
{
	auto pgd = static_cast<PaneGPSData *>(data);

	file_data_unregister_notify_func(bar_pane_gps_notify_cb, pgd);

	g_idle_remove_by_data(pgd);
	bar_pane_gps_clear_marker_queue(pgd);

	file_data_list_free(pgd->selection_list);

	file_data_unref(pgd->fd);
	g_clear_object(&pgd->shumate_map_source);
	g_free(pgd->map_source);
	g_free(pgd->pane.id);
	g_free(pgd);
}

GtkWidget *bar_pane_gps_new(const gchar *id, const gchar *title, const gchar *map_id,
         					const gint zoom, const gdouble latitude, const gdouble longitude,
            				gboolean expanded, gint height)
{
	PaneGPSData *pgd;
	GtkWidget *vbox;
	GtkWidget *status;
	GtkWidget *progress;

	pgd = g_new0(PaneGPSData, 1);

	pgd->pane.pane_set_fd = bar_pane_gps_set_fd;
	pgd->pane.pane_notify_selection = bar_pane_gps_notify_selection;
	pgd->pane.pane_event = bar_pane_gps_event;
	pgd->pane.pane_write_config = bar_pane_gps_write_config;
	pgd->pane.title = bar_pane_expander_title(title);
	pgd->pane.id = g_strdup(id);
	pgd->pane.type = PANE_GPS;
	pgd->pane.expanded = expanded;
	pgd->height = height;

	GtkWidget *frame = gtk_frame_new(nullptr);
	DEBUG_NAME(frame);
	vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);

	pgd->map = shumate_simple_map_new();
	pgd->map_popover_parent = popover_parent_new(GTK_WIDGET(pgd->map));
	pgd->viewport = shumate_simple_map_get_viewport(pgd->map);

	gtk_widget_set_hexpand(pgd->map_popover_parent, TRUE);
	gtk_widget_set_vexpand(pgd->map_popover_parent, TRUE);

	gtk_box_append(GTK_BOX(vbox), pgd->map_popover_parent);

	gq_gtk_container_add(frame, vbox);

	status = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);

	progress = gtk_progress_bar_new();
	gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress), "");
	gtk_progress_bar_set_show_text(GTK_PROGRESS_BAR(progress), TRUE);

	gtk_box_append(GTK_BOX(status), progress);
	gtk_box_append(GTK_BOX(vbox), status);

	pgd->widget = frame;
	pgd->progress = progress;

	g_autofree gchar *user_agent = g_strdup_printf("%s/%s (%s)", GQ_APPNAME, VERSION, GQ_WEBSITE);
	shumate_set_user_agent(user_agent);

	bar_pane_gps_set_map_source(pgd, map_id);

	pgd->marker_layer = shumate_marker_layer_new(pgd->viewport);
	shumate_simple_map_insert_overlay_layer_behind(pgd->map, SHUMATE_LAYER(pgd->marker_layer), nullptr);

	shumate_viewport_set_zoom_level(pgd->viewport, zoom);
	shumate_map_center_on(shumate_simple_map_get_map(pgd->map), latitude, longitude);
	pgd->centre_map_checked = TRUE;
	g_object_set_data_full(G_OBJECT(pgd->widget), "pane_data", pgd, bar_pane_gps_destroy);
	g_signal_connect(G_OBJECT(pgd->widget), "destroy", G_CALLBACK(bar_pane_gps_widget_destroy_cb), nullptr);

	gtk_widget_add_css_class(frame, "frame");

	gtk_widget_set_size_request(pgd->widget, -1, height);

	/* The licence data is in the About page
	 */
	ShumateLicense *license = shumate_simple_map_get_license(SHUMATE_SIMPLE_MAP(pgd->map));
	gtk_widget_add_css_class(GTK_WIDGET(license), "hidden-license");

	auto *click = gtk_gesture_click_new();
	gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(click), GDK_BUTTON_SECONDARY);

	g_signal_connect(click, "pressed",
	    G_CALLBACK(+[](GtkGestureClick*, int, double, double, gpointer data){
		        auto *pgd = static_cast<PaneGPSData*>(data);
		        GtkWidget *menu = bar_pane_gps_menu(pgd);
		        popover_popup(menu);
		    }), pgd);
	gtk_widget_add_controller(GTK_WIDGET(pgd->map), GTK_EVENT_CONTROLLER(click));

	bar_pane_gps_dnd_init(pgd);

	file_data_register_notify_func(bar_pane_gps_notify_cb, pgd, NOTIFY_PRIORITY_LOW);

	pgd->enable_markers_checked = TRUE;
	pgd->centre_map_checked = TRUE;

	return pgd->widget;
}

} // namespace

GtkWidget *bar_pane_gps_new_from_config(const gchar **attribute_names, const gchar **attribute_values)
{
	g_autofree gchar *title = g_strdup(_("GPS Map"));
	g_autofree gchar *map_id = nullptr;
	gboolean expanded = TRUE;
	gint height = 350;
	gint zoom = 7;
	gdouble latitude;
	gdouble longitude;
	/* Latitude and longitude are stored in the config file as an integer of
	 * (actual value * 1,000,000). There is no READ_DOUBLE utility function.
	 */
	gint int_latitude = 54000000;
	gint int_longitude = -4000000;
	g_autofree gchar *id = g_strdup("gps");

	while (*attribute_names)
		{
		const gchar *option = *attribute_names++;
		const gchar *value = *attribute_values++;

		if (READ_CHAR_FULL("title", title))
			continue;
		if (READ_CHAR_FULL("map-id", map_id))
			continue;
		if (READ_INT_CLAMP_FULL("zoom-level", zoom, 1, 20))
			continue;
		if (READ_INT_CLAMP_FULL("latitude", int_latitude, -90000000, +90000000))
			continue;
		if (READ_INT_CLAMP_FULL("longitude", int_longitude, -90000000, +90000000))
			continue;
		if (READ_BOOL_FULL("expanded", expanded))
			continue;
		if (READ_INT_FULL("height", height))
			continue;
		if (READ_CHAR_FULL("id", id))
			continue;

		config_file_error((std::string("Unknown attribute: ") + option + " = " + value).c_str());
		}

	bar_pane_translate_title(PANE_GPS, id, &title);
	latitude = static_cast<gdouble>(int_latitude) / 1000000;
	longitude = static_cast<gdouble>(int_longitude) / 1000000;

	return bar_pane_gps_new(id, title, map_id, zoom, latitude, longitude, expanded, height);
}

void bar_pane_gps_update_from_config(GtkWidget *pane, const gchar **attribute_names,
                                						const gchar **attribute_values)
{
	PaneGPSData *pgd;
	gint zoom = DEFAULT_ZOOM;
	gint int_longitude = 0;
	gint int_latitude = 0;
	gdouble longitude = 0;
	gdouble latitude = 0;

	pgd = static_cast<PaneGPSData *>(g_object_get_data(G_OBJECT(pane), "pane_data"));
	if (!pgd)
		return;

	g_autofree gchar *title = nullptr;
	g_autofree gchar *map_id = nullptr;
	latitude = shumate_location_get_latitude(SHUMATE_LOCATION(pgd->viewport));
	longitude = shumate_location_get_longitude(SHUMATE_LOCATION(pgd->viewport));

	while (*attribute_names)
	{
		const gchar *option = *attribute_names++;
		const gchar *value = *attribute_values++;

		if (READ_CHAR_FULL("title", title))
			continue;
		if (READ_CHAR_FULL("map-id", map_id))
			{
			bar_pane_gps_set_map_source(pgd, map_id);
			continue;
			}
		if (READ_BOOL(pgd->pane, expanded))
			continue;
		if (READ_INT(*pgd, height))
			continue;
		if (READ_CHAR(pgd->pane, id))
			continue;
		if (READ_INT_CLAMP_FULL("zoom-level", zoom, 1, 8))
			{
			shumate_viewport_set_zoom_level(pgd->viewport, zoom);
			continue;
			}
		if (READ_INT_CLAMP_FULL("longitude", int_longitude, -90000000, +90000000))
			{
			longitude = int_longitude / 1000000.0;
			shumate_map_center_on(shumate_simple_map_get_map(pgd->map), latitude, longitude);
			continue;
			}
		if (READ_INT_CLAMP_FULL("latitude", int_latitude, -90000000, +90000000))
			{
			latitude = int_latitude / 1000000.0;
			shumate_map_center_on(shumate_simple_map_get_map(pgd->map), latitude, longitude);
			continue;
			}

		config_file_error((std::string("Unknown attribute: ") + option + " = " + value).c_str());
	}

	if (title)
		{
		bar_pane_translate_title(PANE_GPS, pgd->pane.id, &title);
		gtk_label_set_text(GTK_LABEL(pgd->pane.title), title);
		}

	gtk_widget_set_size_request(pgd->widget, -1, pgd->height);
	bar_update_expander(pane);
}

/* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */
