#include "evolution_sync.h"

gboolean evo2_addrbook_open(evo_environment *env)
{
	ESourceList *sources;
	ESource *source;
	if (!env->adressbook_path)
		return FALSE;
	
  	if (!e_book_get_addressbooks(&sources, NULL)) {
		printf("Report error\n");
		return FALSE;
	}
	
	source = find_source(sources, env->adressbook_path);
	if (!source) {
		printf("Error2\n");
		return FALSE;
	}
	
	env->adressbook = e_book_new(source, NULL);
	
	if(!env->adressbook) {
		evo_debug(env, 1, "failed new open addressbook\n");
		return FALSE;
	}
	
	if (!e_book_open(env->adressbook, TRUE, NULL)) {
		evo_debug(env, 1, "Could not load addressbook\n");
		return FALSE;
		//FIXME Free
	}
	return TRUE;
}

gboolean evo2_addrbook_modify(evo_environment *env, char *data, char *uid, char *uidret, int *uidretlen)
{
	EContact *contact;
	
	if (uidretlen)
		*uidretlen = 0;
	
	if (!data) {
		if (e_book_remove_contact(env->adressbook, uid, NULL))
			return TRUE;
		else
			return FALSE;
	}
	
	if (!uid) {
		contact = e_contact_new_from_vcard(data);
		if (e_book_add_contact(env->adressbook, contact, NULL)) {
			if (uidret) {
				char *luid = e_contact_get_const(contact, E_CONTACT_UID);
				if (luid) {
					strncpy(uidret, luid, 256); // FIXME: 256 is hard coded in syncengine
					evo_debug(env, 2, "uidret after e_book_add_contact: %s\n", uidret);
					*uidretlen = strlen(uidret);
				}
			}
			return TRUE;
		}
	} else {
		contact = e_contact_new_from_vcard(data);
		e_contact_set(contact, E_CONTACT_UID, uid);
		if (e_book_commit_contact(env->adressbook, contact, NULL)) {
			if (uidret) {
				char *luid = e_contact_get_const(contact, E_CONTACT_UID);
				if (luid) {
					strncpy(uidret, luid, 256); // FIXME: 256 is hard coded in syncengine
					printf("new uid after modding %s\n", uidret);
					*uidretlen = strlen(uidret);
				}
			}
			return TRUE;
		}
	}
	return FALSE;
}
