/* gcc -g -O0 test.c -o test `pkg-config --cflags --libs gtk+-3.0` && ./test "tel:+12 345 676 899" */

#include <stdio.h>
#include <string.h>
#include <gtk/gtk.h>

static gint
show_uri (const gchar *uri)
{
	GError *error = NULL;
	guint32 timestamp;

	g_return_if_fail (uri != NULL);

	if (strchr (uri, ':')) {
		gchar *tmp = g_strdup (uri), *str;
		GAppInfo *app_info;

		str = strchr (tmp, ':');
		g_return_val_if_fail (str != NULL, 2);

		*str = '\0';

		app_info = g_app_info_get_default_for_uri_scheme (tmp);
		if (app_info) {
			printf ("Scheme '%s' is handled by:\n"
				"   name: '%s'\n"
				"   display name: '%s'\n"
				"   description: '%s'\n"
				"   executable: '%s'\n"
				"   command line: '%s'\n",
				tmp,
				g_app_info_get_name (app_info),
				g_app_info_get_display_name (app_info),
				g_app_info_get_description (app_info),
				g_app_info_get_executable (app_info),
				g_app_info_get_commandline (app_info));

			if (g_app_info_can_delete (app_info))
				g_app_info_delete (app_info);
		} else {
			fprintf (stderr, "No handler is associated for scheme '%s'\n", tmp);
		}

		g_free (tmp);
	}

	timestamp = gtk_get_current_event_time ();

	if (gtk_show_uri (NULL, uri, timestamp, &error)) {
		printf ("OK, URI '%s' had been shown\n", uri);
		return 0;
	}

	fprintf (stderr, "Failed to show URI '%s': %s\n", uri, error ? error->message : "Unknown error");

	return 3;
}

int
main (int argc, char *argv[])
{
	gtk_init (&argc, &argv);

	if (argc != 2) {
		fprintf (stderr, "Requires one parameter, a URI to open.\n");
		return 1;
	}

	return show_uri (argv[1]);
}
