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

/*
 *  Copyright (C) 2003 Hiroyuki Ikezoe
 *
 *  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 <string.h>

#include "utils.h"
#include "kz-google.h"

#define GOOGLE_URI "http://www.google.com/search?lr=lang_ja&hl=ja&ie=UTF-8&oe=utf8&q=%s"


static gboolean kz_google_parse_from_string (KzBookmark *bookmark,
					     const gchar *buffer,
					     guint length,
					     GError **error);


static KzBookmarkFileType google_file_type =
{
	priority_hint: 0,
	file_type:     "Google",
	is_supported:  NULL,
	init:          NULL,
	from_string:   kz_google_parse_from_string,
	to_string:     NULL,
};


KzBookmarkFileType *
kz_google_get_file_types (gint idx)
{
	if (idx == 0)
		return &google_file_type;
	else
		return NULL;
}


static gboolean
kz_google_parse_from_string (KzBookmark *bookmark,
			     const gchar *buffer, guint length,
			     GError **error)
{
	gchar *find_pos1, *find_pos2;
	gchar **lines = NULL;
	guint line_number = 0;

	g_return_val_if_fail(buffer, FALSE);
	find_pos1 = strstr(buffer, "<!--m-->");
	if (!find_pos1)
		return FALSE;

	lines = g_strsplit(find_pos1 + 8, "<!--m-->", -1);
	while (lines[line_number+1] != NULL)
	{
		KzBookmark *item;

		item = kz_bookmark_new();
		/* kz_bookmark_set_editable(item, FALSE); */

		find_pos1 = strstr(lines[line_number], "<a href=");
		find_pos2  = strstr(lines[line_number], ">");
		if (find_pos1 != NULL && find_pos2 != NULL)
		{
			gchar *uri;
			find_pos1 += 8;
			uri = g_strndup(find_pos1,
					find_pos2 - find_pos1);
			kz_bookmark_set_link(item, uri);
			g_free(uri);
		}
		else
		{
			continue;
		}
		find_pos2++;
		find_pos1 = strstr(find_pos2, "</a>"); /* serach </a> */
		if (find_pos1 != NULL)
		{
			gchar *title = remove_tag(find_pos2, find_pos1 - find_pos2);
			gchar *desc;

			kz_bookmark_set_title(item, title);

			find_pos1 += 4;
			desc = remove_tag(find_pos1, find_pos2 - find_pos1 );
			kz_bookmark_set_description(item, desc);
		}
		kz_bookmark_append(KZ_BOOKMARK(bookmark), item);
		g_object_unref(G_OBJECT(item));
		
		line_number++;
	}

	g_strfreev(lines);	

	return TRUE;
}
