/* Copyright (c) 2008-2013 Tollef Fog Heen <tfheen@err.no>

 eweouz is free software; you can redistribute it and/or modify it
 under the terms of the GNU General Public License version 2 as
 published by the Free Software Foundation.

 eweouz 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
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 02110-1301 USA.
*/

#include <libebook/libebook.h>
#include <glib.h>
#include <locale.h>
#include <string.h>

static gchar *id = NULL;
static gchar *full_name = NULL;
static gchar *nickname = NULL;
static gchar *company = NULL;
static gchar **phones = NULL;
static gchar **emails = NULL;

static GOptionEntry entries[] = 
{
	{ "id", 0, 0, G_OPTION_ARG_STRING, &id, "ID of element to modify, new or new-vcard", "ID" },
	{ "full-name", 0, 0, G_OPTION_ARG_STRING, &full_name, "Full name of person", "full_name" },
	{ "nickname", 0, 0, G_OPTION_ARG_STRING, &nickname, "Nickname of person", "nick" },
	{ "company", 0, 0, G_OPTION_ARG_STRING, &company, "Company of person", "company" },
	{ "phones", 0, 0, G_OPTION_ARG_STRING_ARRAY, &phones, "Phone numbers (all)", "phone" },
	{ "emails", 0, 0, G_OPTION_ARG_STRING_ARRAY, &emails, "Email addresses (all)", "email" },

	{ NULL }
};

/*
Addresses List of        `bbdb-record-addresses'    List of address vectors
          Vectors        `bbdb-record-set-addresses'
Net       List of        `bbdb-record-net'          List of network
address   Strings        `bbdb-record-set-net'      addresses
Notes     String or      `bbdb-record-raw-notes'    String or Association
          Alist          `bbdb-record-set-raw-notes'list of note fields
                                                    (strings)
*/

int main(int argc, char **argv)
{
	EBookClient *client;
	ESourceRegistry *eds_source_registry = NULL;
	EBookClient *ebc;
	ESource *source;
	GSList *contacts;
	GList *sources;
	GList *g, *s;
	GSList *c;
	GError *error = NULL;
	GOptionContext *optioncontext;

	setlocale (LC_ALL, "");

	optioncontext = g_option_context_new ("- whack address book");
	g_option_context_add_main_entries (optioncontext, entries, NULL);
	g_option_context_parse (optioncontext, &argc, &argv, &error);

	if (error != NULL) {
		fprintf(stderr, "%s\n", error->message);
		exit(1);
	}

	eds_source_registry = e_source_registry_new_sync (NULL, &error);
	if (error != NULL) {
		fprintf(stderr, "%s\n", error->message);
		return 1;
	}

	if (id == NULL) {
		fprintf(stderr, "You must provide a filter\n");
		exit(1);
	}

	if (strcmp (id, "new-vcard") == 0 || strcmp(id, "new") == 0) {
		EContact *c;
		GString *vcard = g_string_new("");
		char buf[1024];
		ssize_t r;

		if (strcmp (id, "new-vcard") == 0) {
			while ((r = read(0, buf, 1023)) > 0) {
				buf[r] = '\0';
				vcard = g_string_append(vcard, buf);
			}
			c = e_contact_new_from_vcard(vcard->str);

			if (! c) {
				fprintf(stderr, "Error parsing vcard\n");
				return 1;
			}
		} else if (strcmp (id, "new") == 0) {
			c = e_contact_new ();

			if (full_name) {
				g_object_set(c, "full-name", full_name, NULL);
			}

			if (nickname)
				g_object_set(c, "nickname", nickname, NULL);

			if (emails) {
				gchar **head = emails;
				GList *el = NULL;
				while (*head != NULL) {
					el = g_list_prepend(el, *head);
					head++;
				}
				g_object_set(c, "email", el, NULL);
			}
		}
		source = e_source_registry_ref_default_address_book(eds_source_registry);

		if (! source) {
			return 1;
		}

		ebc = e_book_client_new(source, &error);
		if (error != NULL) {
			fprintf(stderr, "%s\n", error->message);
			return 1;
		}

		e_client_open_sync(E_CLIENT(ebc), TRUE, NULL, &error);
		if (error != NULL) {
			fprintf(stderr, "%s\n", error->message);
			return 1;
		}

		e_book_client_add_contact_sync(ebc, c, NULL, NULL, &error);
		if (error != NULL) {
			fprintf(stderr, "%s\n", error->message);
			return 1;
		}
	} else {
		char *qu = g_strdup_printf ("(is \"id\" \"%s\")", id);

		sources = e_source_registry_list_sources (eds_source_registry, E_SOURCE_EXTENSION_ADDRESS_BOOK);

		for (s = sources ; s; s = s->next) {
			source = E_SOURCE(s->data);
			client = E_BOOK_CLIENT(e_book_client_connect_sync(source, 60, NULL, &error));
			e_book_client_get_contacts_sync(client, qu, &contacts, NULL, &error);

			for (c = contacts; c; c = c->next) {
				if (full_name)
					g_object_set(E_CONTACT(c->data), "full-name", full_name, NULL);
				
				if (nickname)
					g_object_set(E_CONTACT(c->data), "nickname", nickname, NULL);
				
				if (emails != NULL) {
					gchar **head = emails;
					GList *el = NULL;
					
					if (*head[0] == '\0') {
						printf("removing all emails\n");
						head++;
					} else {
						g_object_get(E_CONTACT(c->data), "email", &el, NULL);
					}
					
					while (*head != NULL) {
						printf("appending %s\n", *head);
						el = g_list_prepend(el, *head);
						head++;
					}
					g_object_set(E_CONTACT(c->data), "email", el, NULL);
				}
				e_book_client_modify_contact_sync(client, E_CONTACT(c->data), NULL, &error);
			}
		}
		g_free(qu);
	}
	return 0;
}
