/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * change-presence.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 <stdio.h>

#include <glib.h>

#include <string.h>

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

#include <gio/gio.h>

static GMainLoop *mainloop = NULL;

static DbusmenuClient *client = NULL;

static gchar *presence = NULL;

static void
on_root_changed (DbusmenuClient *menu_client,
				 DbusmenuMenuitem *root_item,
				 gpointer user_data)
{
  const GList *children;
  const GList *walk;
	
  children = dbusmenu_menuitem_get_children (root_item);
	
  for (walk = children;
	   walk != NULL;
	   walk = walk->next)
	{
	  DbusmenuMenuitem *child;
	  const gchar *child_label;
			
	  child = (DbusmenuMenuitem *)walk->data;
	  child_label = dbusmenu_menuitem_property_get (child, "label");

			
	  if (g_strcmp0 (g_utf8_casefold (child_label, strlen (child_label)), 
					 g_utf8_casefold (presence, strlen (presence))) == 0)
		{
		  dbusmenu_menuitem_handle_event (child, "clicked", NULL, time(NULL));
		  
		  g_dbus_connection_flush_sync (g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL), NULL, NULL);
				
		  exit (0);
		}
	}
	
  exit(0);
}


gint
main (gint argc, gchar **argv)
{

  if (argc != 2)
	{
	  printf("Usage: change-presence presence");
	  exit(1);
	}
  
  presence = argv[1];

  g_type_init ();
  
  client = dbusmenu_client_new ("com.canonical.indicator.messages", "/com/canonical/indicator/messages/menu");
  
  g_signal_connect (client, "root-changed",
					G_CALLBACK (on_root_changed),
					NULL);
  
  mainloop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (mainloop);
  
  
  exit (0);
}
