/* -*- 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>
#define __USE_XOPEN
#include <time.h>

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

typedef enum {
	STATE_START   = (1 << 0),
	STATE_ROOT    = (1 << 1),
	STATE_CHANNEL = (1 << 2),
	STATE_ITEM    = (1 << 3),
	STATE_TITLE   = (1 << 4),
	STATE_LINK    = (1 << 5),
	STATE_DESC    = (1 << 6),
	STATE_DCDATE  = (1 << 7),
	STATE_END     = (1 << 8),
	STATE_ERROR   = (1 << 9)
} ParseState;

typedef struct _ParseContext ParseContext;
struct _ParseContext
{
	/* parser state information */
	ParseState state;
	ParseState current_state;

	KzBookmark *bookmark;
};


static gboolean kz_rss_is_supported      (KzBookmark  *bookmark,
					  const gchar *buffer);
static gboolean kz_rss_parse_from_string (KzBookmark  *bookmark,
					  const gchar *buffer,
					  guint        length,
					  GError     **error);
static gchar   *kz_rss_get_encoding      (gchar       *src);
static gchar   *kz_rss_convert_to_utf8   (gchar       *src,
					  guint        src_len,
					  guint       *dest_len);


static KzBookmarkFileType rss_file_type =
{
	priority_hint: 0,
	file_type:     "RSS",
	init:          NULL,
	is_supported:  kz_rss_is_supported,
	from_string:   kz_rss_parse_from_string,
	to_string:     NULL,
};


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


static gboolean
kz_rss_is_supported(KzBookmark *bookmark, const gchar *buf)
{
	const gchar *pos;

	g_return_val_if_fail(buf, FALSE);

	if (strncmp(buf, "<?xml", 5)) return FALSE;

	pos = buf;

	/* find first element */
	do
		pos = strchr(pos + 1, '<');
	while (pos && pos[1] == '!');

	if (!pos) return FALSE;

	if (!strncmp(pos, "<rdf",4) || !strncmp(pos, "<rss",4))
		return TRUE;

	return FALSE;
}

static void
start_element_handler (GMarkupParseContext *context,
		       const gchar         *element_name,
		       const gchar        **attribute_names,
		       const gchar        **attribute_values,
		       gpointer             user_data,
		       GError             **error)
{
	ParseContext *ctx = user_data;

	ctx->current_state = STATE_ERROR;
	
	switch (element_name[0])
	{
	 case 'r':
		if (ctx->state == STATE_START && 
		    (!strcmp(element_name, "rdf:RDF") ||
		     !strcmp(element_name, "rss")))
		{
			ctx->state = STATE_ROOT;
			ctx->current_state = STATE_ROOT;
		}
		break;
	 case 'i':
		if ((ctx->state & STATE_ROOT) && !strcmp(element_name, "item")
		    && strcmp(element_name, "items"))
		{
			KzBookmark *item;

			ctx->state |= STATE_ITEM;
			ctx->current_state = STATE_ITEM;

			/* append new KzRSSItem */
			item = kz_bookmark_new();
			kz_bookmark_set_editable(item, FALSE);
			kz_bookmark_append(KZ_BOOKMARK(ctx->bookmark), item);
			g_object_unref(G_OBJECT(item));
		}
		break;
	 case 'c':
		if ((ctx->state & STATE_ROOT) && !strcmp(element_name, "channel"))
		{
			ctx->state |= STATE_CHANNEL;
			ctx->current_state = STATE_CHANNEL;
		}
		break;
	 case 't':
		if (!strcmp(element_name, "title"))
		{
			ctx->state |= STATE_TITLE;
			ctx->current_state = STATE_TITLE;
		}
		break;
	 case 'l':
		if (!strcmp(element_name, "link"))
		{
			ctx->state |= STATE_LINK;
			ctx->current_state = STATE_LINK;
		}
		break;
	 case 'd':
		if (!strcmp(element_name, "description"))
		{
			ctx->state |= STATE_DESC;
			ctx->current_state = STATE_DESC;
		}
		else if (!strcmp(element_name, "dc:date"))
		{
			ctx->state |= STATE_DCDATE;
			ctx->current_state = STATE_DCDATE;
		}
		break;
	}
}

static void
end_element_handler (GMarkupParseContext *context,
		     const gchar         *element_name,
		     gpointer             user_data,
		     GError             **error)
{
	ParseContext *ctx = user_data;

	ctx->state = ctx->state & ~(ctx->current_state);
	ctx->current_state = STATE_ERROR;
}

static void 
text_handler (GMarkupParseContext *context,
	      const gchar          *text,
	      gsize                 text_len,
	      gpointer              user_data,
	      GError              **error)
{
	ParseContext *ctx = user_data;

	if (ctx->current_state == STATE_ERROR)
		return;

	if (ctx->state & STATE_ITEM)
	{
		GList *list = kz_bookmark_get_children(KZ_BOOKMARK(ctx->bookmark));
		guint pos = g_list_length(list);
		KzBookmark *item = g_list_nth_data(list, pos - 1);
		gchar *str;

		switch (ctx->current_state)
		{
		 case STATE_TITLE:
			str = g_strndup(text, text_len);
			kz_bookmark_set_title(item, str);
			g_free(str);
			break;
		 case STATE_LINK:
			str = g_strndup(text, text_len);
			kz_bookmark_set_link(item, str);
			g_free(str);
			break;
		 case STATE_DESC:
			str = remove_tag((gchar*)text, text_len);
			kz_bookmark_set_description(item, str);
			g_free(str);
			break;
		 case STATE_DCDATE:
			{
				struct tm t;
				strptime(text,
					 "%Y-%m-%dT%H:%M:%S", &t);
				kz_bookmark_set_last_modified(item, (guint)mktime(&t));
				break;
			}
		default:
			break;
		}
			
		g_list_free(list);
	}
	else if (ctx->state & STATE_CHANNEL)
	{
		gchar *str = g_strndup(text, text_len);
		switch (ctx->current_state)
		{
		case STATE_TITLE:
			kz_bookmark_set_document_title(KZ_BOOKMARK(ctx->bookmark), str);
			break;
		case STATE_LINK:
			kz_bookmark_set_link(KZ_BOOKMARK(ctx->bookmark), str);
			break;
		case STATE_DESC:
			kz_bookmark_set_description(KZ_BOOKMARK(ctx->bookmark), str);
			break;
		 case STATE_DCDATE:
			{
				struct tm t;
				strptime(text,
					 "%Y-%m-%dT%H:%M:%S", &t);
				kz_bookmark_set_last_modified(KZ_BOOKMARK(ctx->bookmark),
							      (guint)mktime(&t));
				break;
			}
		default:
			break;
		}
		g_free(str);
	}
}

static GMarkupParser ui_parser = {
	start_element_handler,
	end_element_handler,
	text_handler,
	NULL,
	NULL
};

gboolean
kz_rss_parse_from_string (KzBookmark *bookmark,
			  const gchar *buffer, guint length,
			  GError **error)
{
	gchar *utf8_body = NULL;
	/* gchar *body; */
	guint utf8_len;

	ParseContext ctx = { 0 };
	GMarkupParseContext *context;

	g_return_val_if_fail(buffer != NULL, FALSE);

	/* check encoding and convert if need */
	utf8_body = kz_rss_convert_to_utf8((gchar*)buffer, length, &utf8_len);

	ctx.state = STATE_START;
	ctx.current_state = STATE_START;
	ctx.bookmark = bookmark;

	context = g_markup_parse_context_new(&ui_parser, 0, &ctx, NULL);
	if (length < 0)
		length = strlen(buffer);
	
	if (utf8_body)
	{
		if (g_markup_parse_context_parse(context, utf8_body, utf8_len, error))
		{
			g_markup_parse_context_end_parse(context, error);
		}
		g_free(utf8_body);
	}
	else
	{
		if (g_markup_parse_context_parse(context, buffer, length, error))
		{
			g_markup_parse_context_end_parse(context, error);
		}
	}

	g_markup_parse_context_free (context);

	return TRUE;
}

static gchar *
kz_rss_get_encoding (gchar *src)
{
	gchar *encoding = NULL;
	gchar **lines = NULL;
	gchar *prev_pos, *next_pos;
	
	g_return_val_if_fail(src, NULL);

	lines = g_strsplit(src, "\n", 1);
	prev_pos =  strstr(lines[0], "encoding");
	if (prev_pos)
	{
		while (*prev_pos != '"' && *prev_pos != '\0')
		{
			prev_pos++;
		}
		if (prev_pos != '\0')
		{
			prev_pos++;
			next_pos = strchr(prev_pos, '"');
			if (next_pos)
				encoding = g_strndup(prev_pos, 
						     next_pos - prev_pos);
			if (!strcasecmp(encoding, "UTF-8"))
			{
				g_free(encoding);
				encoding = NULL;
			}
		}
	}

	g_strfreev(lines);
	return encoding;
}

static gchar *
kz_rss_convert_to_utf8 (gchar *src, guint src_len, guint *dest_len)
{
	gchar *dest = NULL;
	gchar *encoding = NULL;
	guint read_len;

	encoding = kz_rss_get_encoding(src);

	if (encoding)
	{
		dest = g_convert(src, src_len, "UTF-8", encoding,
				 &read_len, dest_len, NULL);
		g_free(encoding);
	}

	return dest;
}
