//Listener to be used for 648623, based on pyatspi one uploaded at bug 706391
#include "atspi/atspi.h"
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

pid_t child_pid;
AtspiEventListener *listener;
AtspiEventListener *listener2;

static AtspiAccessible*
find_child_slider(AtspiAccessible *accessible)
{
  AtspiAccessible *child = NULL;
  int i = 0;

  for (i = 0; i < atspi_accessible_get_child_count (accessible, NULL); i++) {
    child = atspi_accessible_get_child_at_index (accessible, i, NULL);
    if (atspi_accessible_get_role (child, NULL) == ATSPI_ROLE_SLIDER)
      break;
  }

  return child;
}

static void
print_accessible_info (AtspiAccessible *accessible)
{
  gchar *name = "NULL";
  gchar *role_name = "NULL";
  gchar *current_value = NULL;
  AtspiValue *value_iface = NULL;

  if (accessible != NULL) {
    name = atspi_accessible_get_name (accessible, NULL);
    role_name = atspi_accessible_get_role_name (accessible, NULL);
    value_iface = atspi_accessible_get_value_iface (accessible);
    if (value_iface != NULL)
      current_value = g_strdup_printf ("%f", atspi_value_get_current_value (value_iface, NULL));
    else
      current_value = g_strdup_printf ("NO VALUE");
  }

  g_print ("(%s, %s, %s)", name, role_name, current_value);
  g_free (current_value);
}

static void
on_notify (const AtspiEvent *event, void *data)
{
  g_print ("Change on accessible value: ");
  print_accessible_info (event->source);
  g_print ("\n");
}

static void
on_event (const AtspiEvent *event, void *data)
{
  AtspiAccessible *application = NULL;
  AtspiAccessible *slider_child = NULL;

  if (event->source == NULL)
    return;

  //we only want focus-in not out
  if (!event->detail1)
    return;

  application = atspi_accessible_get_application (event->source, NULL);
  if (application == NULL)
    return;

  if (g_strcmp0 (atspi_accessible_get_name (application, NULL), "gnome-shell") != 0)
    return;

  print_accessible_info (event->source);
  slider_child = find_child_slider (event->source);
  print_accessible_info (slider_child);
  g_print ("\n");
}

int main()
{
  atspi_init ();

  listener = atspi_event_listener_new (on_event, NULL, NULL);
  listener2 = atspi_event_listener_new (on_notify, NULL, NULL);
  atspi_event_listener_register (listener, "object:state-changed:focused", NULL);
  atspi_event_listener_register (listener, "object:state-changed:selected", NULL);
  atspi_event_listener_register (listener2, "object:property-change:accessible-value", NULL);
  atspi_event_main ();

  return 0;
}
