/* liblivejournal - a client library for LiveJournal.
 * Copyright (C) 2003 Evan Martin <evan@livejournal.com>
 *
 * vim: tabstop=4 shiftwidth=4 noexpandtab :
 */

#include <glib.h>
#include <stdlib.h> /* atoi */

#include "syncitems.h"

static void
read_syncitems(LJSyncItems *syncitems, LJResult *result) {
	GSList *tail;
	int count, i;
	LJSyncItem *syncitem;
	time_t lastsync = 0;

	count = lj_result_get_int(result, "sync_count");

	tail = g_slist_last(syncitems->items);
	for (i = 1; i <= count; i++) {
		char *item = lj_result_getf(result, "sync_%d_item", i);
		int id = atoi(item+2);
		struct tm tm;
		
		/* skip duplicates. */
		if (tail && ((LJSyncItem*)tail->data)->id == id) {
			g_print("skipping dup.\n");
			continue;
		}

		syncitem = g_new0(LJSyncItem, 1);
		if (item[0] == 'L') {
			syncitem->type = LJ_SYNCITEM_TYPE_ENTRY;
		} else {
			syncitem->type = LJ_SYNCITEM_TYPE_OTHER;
		}
		syncitem->id = id;
		lj_ljdate_to_tm(lj_result_getf(result, "sync_%d_time", i), &tm);
		syncitem->time = lj_timegm(&tm);
		if (syncitem->time > lastsync)
			lastsync = syncitem->time;

		if (syncitems->items) {
			g_slist_append(tail, syncitem);
			tail = tail->next;
		} else {
			tail = syncitems->items = g_slist_append(tail, syncitem);
		}
	}
	if (lastsync > 0) {
		g_free(syncitems->lastsync);
		syncitems->lastsync = lj_tm_to_ljdate(gmtime(&lastsync));
	}
}


static void
parse_result(LJVerb *verb) {
	LJSyncItems *syncitems = (LJSyncItems*)verb;
	LJResult *result = verb->result;
	read_syncitems(syncitems, result);
	syncitems->count = lj_result_get_int(result, "sync_count");
	syncitems->total = lj_result_get_int(result, "sync_total");
}

LJSyncItems*
lj_syncitems_new(LJUser *user, const char *usejournal, const char *lastsync) {
	LJSyncItems *syncitems = g_new0(LJSyncItems, 1);
	LJVerb *verb = (LJVerb*)syncitems;
	LJRequest *request;

	lj_verb_init(verb, user, "syncitems", FALSE, parse_result);
	request = verb->request;

	if (lastsync)
		lj_request_add(request, "lastsync", lastsync);

	return syncitems;
}

void
lj_syncitems_free(LJSyncItems *syncitems, gboolean free_items) {
	lj_verb_free_contents((LJVerb*)syncitems);
	g_free(syncitems->lastsync);
	if (free_items) {
		g_slist_foreach(syncitems->items, (GFunc)g_free, NULL);
		g_slist_free(syncitems->items);
	}
	g_free(syncitems);
}

