/* isync.c - file containing 'legacy' isync routines 
 *
 * contents of this file is taken from isync-0.4
 *
 * Copyright (C) 2000 Michael R. Elkins <me@mutt.org>
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "isync.h"
#include "list.h"
#include "imap.h"

void free_message(message_t * msg)
{
	message_t *tmp;

	while (msg) {
		tmp = msg;
		msg = msg->next;
		if (tmp->file)
			free(tmp->file);
		free(tmp);
	}
}

int parse_fetch(imap_t * imap, list_t * list)
{
	list_t *tmp;
	unsigned int uid = 0;
	unsigned int mask = 0;
	unsigned int size = 0;
	message_t *cur;

	if (!is_list(list))
		return -1;

	for (tmp = list->child; tmp; tmp = tmp->next) {
		if (!is_atom(tmp))
			continue;
		if (!strcmp("UID", tmp->val)) {
			tmp = tmp->next;
			if (is_atom(tmp)) {
				uid = atoi(tmp->val);
				if (uid < imap->minuid) {
					/* already saw this message */
					printf("already seen\n");
					return 0;
				} else if (uid > imap->maxuid)
					imap->maxuid = uid;
			} else
				puts("Error, unable to parse UID");
		} else if (!strcmp("FLAGS", tmp->val)) {
			list_t *flags;
			tmp = tmp->next;
			if (!is_list(tmp)) {
				puts("Error, unable to parse FLAGS");
				continue;
			}
			flags = tmp->child;

			for (; flags; flags = flags->next) {
				if (!is_atom(flags)) {
					puts
					    ("Error, unable to parse FLAGS list");
					continue;
				}
				if (!strcmp("\\Seen", flags->val))
					mask |= D_SEEN;
				else if (!strcmp("\\Flagged", flags->val))
					mask |= D_FLAGGED;
				else if (!strcmp("\\Deleted", flags->val))
					mask |= D_DELETED;
				else if (!strcmp("\\Answered", flags->val))
					mask |= D_ANSWERED;
				else if (!strcmp("\\Draft", flags->val))
					mask |= D_DRAFT;
				else if (!strcmp("\\Recent", flags->val))
					mask |= D_RECENT;
				else
					printf
					    ("Warning, unknown flag %s\n",
					     flags->val);
			}
		} else if (!strcmp("RFC822.SIZE", tmp->val)) {
			tmp = tmp->next;
			if (is_atom(tmp))
				size = atol(tmp->val);
		}
	}

	cur = calloc(1, sizeof(message_t));
	cur->next = imap->msgs;
	imap->msgs = cur;

	if (mask & D_DELETED)
		imap->deleted++;

	cur->uid = uid;
	cur->flags = mask;
	cur->size = size;

	return 0;
}
