#include "evolution_sync.h"

gboolean evo2_tasks_open(evo_environment *env)
{
	ESourceList *sources;
	ESource *source;
	if (!env->tasks_path)
		return FALSE;
	
  	if (!e_cal_get_sources(&sources, E_CAL_SOURCE_TYPE_TODO, NULL)) {
  		evo_debug(env, 1, "Unable to get sources for tasks");
		return FALSE;
	}
	
	source = find_source(sources, env->tasks_path);
	if (!source) {
		evo_debug(env, 1, "Unable to find source for tasks");
		return FALSE;
	}
	
	env->tasks = e_cal_new(source, E_CAL_SOURCE_TYPE_TODO);
	if(!env->tasks) {
		evo_debug(env, 1, "failed new tasks");
		return FALSE;
	}
	
	if(!e_cal_open(env->tasks, FALSE, NULL)) {
		evo_debug(env, 1, "failed to open tasks");
		return FALSE;
	}
	return TRUE;
}

gboolean evo2_tasks_modify(evo_environment *env, char *data, char *uid, char *uidret, int *uidretlen)
{
	ECalComponent *cal;
	icalcomponent *icomp;
	uidret = NULL;
	if (uidretlen)
		*uidretlen = 0;

	if (!data) {
		if (e_cal_remove_object(env->tasks, uid, NULL))
			return TRUE;
		else
			return FALSE;
	}

	//Remove BEGIN:VCALENDAR
	if (!strncmp("BEGIN:VCALENDAR", data, 15)) {
		memmove(data, data + 17, strlen(data) +1 - 17);
		data[strlen(data) - 19] = 0;
	}	

	if (!uid) {
		ECalComponent *ecal = e_cal_component_new();
		icomp = icalcomponent_new_from_string(data);
		e_cal_component_set_icalcomponent(ecal, icomp);
		if(!icomp)
			return FALSE;
		char *luid = NULL;
		if (e_cal_create_object(env->tasks, icomp, &luid, NULL)) {
			if (uidret) {
                                if (luid) {
                                        strncpy(uidret, luid, 256); // FIXME: 256 is hard coded in syncengine
                                        evo_debug(env, 2, "uidret after e_cal_create_object: %s\n", uidret);
                                        *uidretlen = strlen(uidret);
                                }
                        }
                        return TRUE;
		}
	} else {
		ECalComponent *ecal = e_cal_component_new();
		icomp = icalcomponent_new_from_string(data);
		e_cal_component_set_icalcomponent(ecal, icomp);
		e_cal_component_set_uid(ecal, uid);
		if(!icomp)
			return FALSE;
		if (e_cal_modify_object(env->tasks, icomp, CALOBJ_MOD_ALL, NULL))
			return TRUE;
	}
	return FALSE;
}
