/* Test GtkDialog
 * Build with gcc `pkg-config --cflags --libs gtk+-3.0` -o gtk-dialog-test gtk-dialog-test.c
 */

#include <glib.h>
#include <json-glib/json-glib.h>
#include <gio/gunixinputstream.h>

int
main (int   argc   G_GNUC_UNUSED,
      char *argv[] G_GNUC_UNUSED)
{
  static const gchar *id = "org.gnome.ControlCenter";
  gchar *provider, *identity;
  GError *error = NULL;
  GApplication *gnomecc;
  GVariant *params, *extra;
  GVariantBuilder *b;
  JsonNode *json;
  JsonObject *obj;
  JsonParser *parser;
  GInputStream *input;

  g_type_init();

  parser = json_parser_new ();
  input = g_unix_input_stream_new (0, FALSE);
  g_debug ("Waiting for account data on stdin...");

  if (!json_parser_load_from_stream (parser, input, NULL, &error))
    g_error ("Unable to parse JSON from stdin: %s (%s, %d)",
        error->message, g_quark_to_string (error->domain), error->code);

  json = json_parser_get_root (parser);
  if (json == NULL)
    g_error ("Unable to find JSON data on stdin");

  obj = json_node_get_object (json);
  provider = g_strdup (json_object_get_string_member (obj, "provider"));
  identity = g_strdup (json_object_get_string_member (obj, "identity"));
  json_object_remove_member (obj, "provider");
  json_object_remove_member (obj, "identity");

  g_debug ("provider: %s", provider);
  g_debug ("identity: %s", identity);
  extra = json_gvariant_deserialize (json, NULL, NULL);

  b = g_variant_builder_new (G_VARIANT_TYPE ("av"));
  g_variant_builder_add (b, "v", g_variant_new_string(provider));
  g_variant_builder_add (b, "v", g_variant_new_string(identity));
  g_variant_builder_add (b, "v", extra);
  params = g_variant_builder_end (b);

  gnomecc = g_application_new (id, G_APPLICATION_IS_LAUNCHER);
  if (!g_application_register (gnomecc, NULL, &error))
    g_error ("Failed to register launcher for %s: %s", id, error->message);
  g_action_group_activate_action (G_ACTION_GROUP (gnomecc), "online-accounts-new", params);

  return 0;
}
