/* -*- Compile-command: "valac --pkg libebook-1.2 --pkg libedataserver-1.2 create-eds-contact.vala" -*- */

using E;

class Test : GLib.Object
{
  private E.BookClient _addressbook;
  private E.SourceGroup _source_group;
  private E.Source _source;
  private MainLoop _loop;

  public void run ()
    {
      this._loop = new MainLoop ();
      Idle.add (this.do_run);
      this._loop.run ();
    }

  public bool do_run ()
    {
      this._really_run ();
      return false;
    }

  private async void _really_run ()
    {
      try
        {
          yield this._prepare_source ();
          this._addressbook = new E.BookClient (this._source);
          yield this._addressbook.open (false, null);
          if (this._addressbook.is_opened () == true)
            {
              yield this._add_contact ();
            }
          else
            {
              GLib.stdout.printf ("Book not opened. Sigh.\n");
              this._loop.quit ();
            }
        }
      catch (GLib.Error e)
        {
          GLib.stdout.printf ("Ooops: %s\n", e.message);
        }
    }

  private async void _prepare_source ()
    {
      this._source = new E.Source.with_absolute_uri ("Test",
          "local:///tmp/testing");
    }

  private async void _add_contact ()
    {
      E.Contact contact = new E.Contact ();
      contact.set (E.Contact.field_id ("full_name"), "Some Dude");
      string added_uid = "";
      try
        {
         var result = yield this._addressbook.add_contact (contact,
              out added_uid);

          if (result)
            {
              GLib.stdout.printf ("\n\nadded_uid = %s\n\n", added_uid);
              GLib.stdout.printf ("\n\nfetched uid = %s\n\n",
                  (string) contact.get (E.Contact.field_id ("id")));
            }
          else
            {
              GLib.stdout.printf ("Failed to create a contact\n");
            }
        }
      catch (GLib.Error e)
        {
          GLib.stdout.printf ("Ooops: %s\n", e.message);
        }
      finally
        {
          this._loop.quit ();
        }
    }

  public static int main ()
    {
      Test t = new Test ();
      t.run ();
      return 0;
    }
}