/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * unity-webapps-action-invoker.c
 * Copyright (C) Canonical LTD 2011
 *
 * Author: Robert Carr <racarr@canonical.com>
 *
unity-webapps 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 3 of the License, or
 * (at your option) any later version.
 *
 * unity-webapps 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 program.  If not, see <http://www.gnu.org/licenses/>.";
 */
#include <stdlib.h>
#include <string.h>

#include "unity-webapps-service.h"
#include "unity-webapps-context.h"

#include <glib/gstdio.h>

#include <time.h>

#include <libdbusmenu-glib/menuitem.h>
#include <libdbusmenu-glib/client.h>

static gchar *application = NULL;
const gchar *action = NULL;

GDBusMenuModel *root = NULL;
GActionGroup *group;

static gboolean
quit_and_flush (gpointer user_data)
{
	while (g_main_context_pending (NULL))
		{
			g_main_context_iteration (NULL, TRUE);
		}
	g_dbus_connection_flush_sync (g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL), NULL, NULL);

	exit (0);

	return FALSE;
}

static gboolean
invoke_action (gpointer data)
{
	gchar **it;
	for (it = g_action_group_list_actions (group); *it; it++) {
		if (!g_str_has_prefix (*it, application))
			continue;
		if (action)
			{
				if (g_strrstr (*it, ".source."))
					{
						gchar *name = g_strrstr (*it, ".source.") + strlen (".source.");
						if (g_strcmp0 (name, action) == 0)
							g_action_group_activate_action (group, *it, NULL);
					}
			}
		else
			{
				if (g_str_has_suffix (*it, ".launch"))
					g_action_group_activate_action (group, *it, NULL);
			}
	}

	g_timeout_add_seconds(1, quit_and_flush, NULL);

	return FALSE;
}

static void
make_client ()
{
	GDBusConnection *connection = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
	root = g_dbus_menu_model_get (connection, "com.canonical.indicator.messages", "/com/canonical/indicator/messages/menu");

	group = G_ACTION_GROUP (g_dbus_action_group_get (connection,"com.canonical.indicator.messages", "/com/canonical/indicator/messages/menu"));

	g_action_group_list_actions (group);

	g_timeout_add_seconds (1, invoke_action, NULL);
}


gint
main (gint argc, gchar **argv)
{
	if (argc == 2)
		{
			application = argv[1];
			action = NULL;
		}
	else if (argc == 3)
		{
			application = argv[1];
			action = argv[2];
		}
	else
		{
			g_printf ("Usage: indicator-action-invoker application (action?)");
			exit (1);
		}

	g_type_init ();

	make_client ();

	g_main_loop_run (g_main_loop_new (NULL, FALSE));

	return 0;
}
