#include <stdlib.h>
#include <string.h>
#include <libebook/e-book.h>

int tests = 0, failed = 0;

static void
check(EContact *contact, EContactField field, const char *value)
{
	const char *cached, *name;
	char *live;
	
	name = e_contact_field_name(field);
	cached = e_contact_get_const(contact, field);
	tests++;
	if (!((value == NULL && cached == NULL) ||
		((value && cached) && !strcmp (value, cached)))) {
		printf("%s: cached value failed: got %s, expected %s\n",
		    name, cached, value);
		failed++;
	}
	live = e_contact_get(contact, field);
	tests++;
	if (!((value == NULL && live == NULL) ||
		((value && live) && !strcmp (value, live)))) {
		printf("%s: live value failed: got %s, expected %s\n",
		    name, live, value);
		failed++;
	}
	if (!live)
		g_free(live);
}


static void
test_ordering(EContact *contact, EContactField field1, EContactField field2)
{
	int failed = 0;
	const char *phone;

	e_contact_set(contact, field1, "123");
	check (contact, field1, "123");

	e_contact_set(contact, field2, "456");
	check (contact, field1, "123");
	check (contact, field2, "456");

	//printf("contact: %s", e_vcard_to_string((EVCard *)contact, EVC_FORMAT_VCARD_30));

	e_contact_set(contact, field1, "987");
	check (contact, field1, "987");
	check (contact, field2, "456");
	e_contact_set(contact, field2, "654");
	check (contact, field1, "987");
	check (contact, field2, "654");

	/* now check blanking out field1 and checking field2 takes its place */
	e_contact_set(contact, field1, NULL);
	phone = e_contact_get_const (contact, field1);
	check (contact, field1, "654");
	/* this one fails because the field2 value is cached and is cache is
	 * not updated when field1 is deleted, causing field2 to be deleted.
	 */
	check (contact, field2, NULL);
	e_contact_set(contact, field1, NULL);
	check (contact, field1, NULL);
	check (contact, field2, NULL);
}


int
main (int argc, char **argv)
{
	EContact *contact;

	g_type_init ();

	contact = e_contact_new_from_vcard ("");

	test_ordering(contact, E_CONTACT_PHONE_HOME, E_CONTACT_PHONE_HOME_2);
	test_ordering(contact, E_CONTACT_PHONE_BUSINESS, E_CONTACT_PHONE_BUSINESS_2);
	test_ordering(contact, E_CONTACT_EMAIL_1, E_CONTACT_EMAIL_2);

	printf("tests: %d, failed: %d\n", tests, failed);
	return (failed == 0);
}

