/*
	Copyright (c) 2010 by Dennis Schridde

	This file is part of dovecot-metadata.

	dovecot-metadata is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	dovecot-metadata 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 Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with dovecot-metadata.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "imap-arg-ext.h"

#include <stdlib.h>

bool
imap_arg_get_astringlist(const struct imap_arg *arg, const char ***list_r) {
	i_assert(list_r != NULL);
	if (list_r == NULL) {
		return false;
	}

	if (*list_r != NULL) {
		free(*list_r);
		*list_r = NULL;
	}

	size_t list_size = 0;

	if (arg->type == IMAP_ARG_LIST) { // entries
		const struct imap_arg *arglist = NULL;
		if (!imap_arg_get_list(arg, &arglist)) {
			return false;
		}

		while (arglist[list_size].type != IMAP_ARG_EOL) {
			const char *astring = NULL;
			if (!imap_arg_get_astring(&arglist[list_size], &astring)) {
				free(*list_r);
				*list_r = NULL;
				return false;
			}

			*list_r = realloc(*list_r, (list_size+2)*sizeof(*list_r));
			if (*list_r == NULL) {
				return false;
			}

			(*list_r)[list_size] = astring;

			list_size++;
		}
	}
	else if (IMAP_ARG_TYPE_IS_ASTRING(arg->type)) {
		const char *astring = NULL;
		if (!imap_arg_get_astring(arg, &astring)) {
			return false;
		}

		*list_r = realloc(*list_r, (list_size+2)*sizeof(*list_r));
		if (*list_r == NULL) {
			return false;
		}

		(*list_r)[list_size] = astring;

		list_size++;
	}
	else {
		return false;
	}

	if (*list_r == NULL) {
		return false;
	}

	(*list_r)[list_size] = NULL;

	return true;
}
