/* This file is part of GNU Pies.
   Copyright (C) 2007-2022 Sergey Poznyakoff

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

   GNU Pies 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Pies.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <c-ctype.h>

static int
time_multiplier(const char *str, unsigned *m, unsigned *plen)
{
	static struct timetab {
		char *name;
		unsigned mul;
	} tab[] = {
		{ "seconds", 1 },
		{ "minutes", 60 },
		{ "hours", 60*60 },
		{ "days",  24*60*60 },
		{ "weeks", 7*24*60*60 },
		{ "months", 31*7*24*60*60 },
		{ NULL }
	};
	struct timetab *p;
	int slen;

	for (slen = 0; str[slen]; slen++)
		if (c_isspace(str[slen]))
			break;

	for (p = tab; p->name; p++) {
		if (p->name[0] == c_tolower(str[0])) {
			int nlen = strlen(p->name);

			if (nlen > slen)
				nlen = slen;
			
			if (strncasecmp(p->name, str, nlen) == 0) {
				*m = p->mul;
				if (plen)
					*plen = nlen;
				return 0;
			}
		}
	}
	return 1;
}

int
parse_time_interval(const char *str, time_t *pint, const char **endp)
{
	int rc = 0;
	time_t interval = 0;
	
	while (*str) {
		char *p;
		unsigned long n;
		unsigned mul, len;

		while (*str && c_isspace(*str))
			str++;

		if (!c_isdigit(*str) && time_multiplier(str, &mul, &len) == 0) {
			n = 1;
			str += len;
		} else {
			n = strtoul(str, &p, 10);
			if (*p && !c_isspace(*p)) {
				str = p;
				rc = 1;
				break;
			}

			while (*p && c_isspace(*p))
				p++;

			str = p;
			if (*str) {
				if ((rc = time_multiplier(str, &mul, &len)))
					break;
				str += len;
			} else
				mul = 1;
		}
		interval += n*mul;
	}

	if (rc && endp)
		*endp = str;
	*pint = interval;
	return rc;
}

