/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/*
 *  Copyright (C) 2003 Takuro Ashie
 *
 *  This program 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 2, or (at your option)
 *  any later version.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */



#include "kz-bookmark-filter.h"

#include <string.h>
#include <ctype.h>
#include <sys/types.h>

#include "kazehakase.h"
#include "kz-profile.h"
#include "utils.h"
#include "glib-utils.h"

#ifndef REG_NOERROR
#define REG_NOERROR (0)
#endif


typedef enum {
	KZ_BOOKMARK_FILTER_NONE,
	KZ_BOOKMARK_FILTER_REGEX_HREF,
	KZ_BOOKMARK_FILTER_REGEX_ELEMENT
} KzBookmarkFilterType;


static KzBookmarkFilterType
detect_filter_type (const gchar *key)
{
	const gchar *known_keys[] = {
		NULL,
		"filter_href_regex",
		"filter_element_regex"
	};
	gint i;

	g_return_val_if_fail(key && *key, KZ_BOOKMARK_FILTER_NONE);

	for (i = 1; i < G_N_ELEMENTS(known_keys); i++)
	{
		if (key_seems_sequential (key, known_keys[i]))
			return i;
	}

	return KZ_BOOKMARK_FILTER_NONE;
}


gboolean
kz_bookmark_filter_out (KzBookmark *bookmark)
{
	GRegex *regex;
	GList *list, *node;
	const gchar *title, *uri;

	g_return_val_if_fail(KZ_IS_BOOKMARK(bookmark), FALSE);

	title = kz_bookmark_get_title(bookmark);
	uri   = kz_bookmark_get_link(bookmark);

	list = kz_profile_enum_key(KZ_GET_GLOBAL_PROFILE, "ExtractLinks", FALSE);

	for (node = list; node; node = g_list_next(node))
	{
		const gchar *key = node->data;
		const gchar *str = NULL;
		gchar *exp;
		gboolean match;
		KzBookmarkFilterType key_type;

		if (!key || !*key) continue;

		key_type = detect_filter_type(key);

		switch (key_type) {
		case KZ_BOOKMARK_FILTER_REGEX_HREF:
			str = uri;
			break;
		case KZ_BOOKMARK_FILTER_REGEX_ELEMENT:
			str = title;
			break;
		default:
			break;
		}

		if (!str || !*str) continue;

		exp = kz_profile_get_string(KZ_GET_GLOBAL_PROFILE,
					    "ExtractLinks", key);

		regex = g_regex_new(exp, 0, 0, NULL);

		match = g_regex_match(regex, str, 0, NULL);

		g_free(exp);
		g_regex_free(regex);

		if (match)
			return TRUE;
	}

	return FALSE;
}
