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

#include <string.h>
#include <glib/gi18n.h>

#include "gobject-utils.h"
#include "kz-navi.h"
#include "kazehakase.h"
#include "bookmarks/kz-bookmark.h"
#include "bookmarks/kz-bookmark-file.h"

static void kz_navi_class_init   (KzNaviClass  *klass);
static void kz_navi_init         (KzNavi       *navi);
static void kz_navi_dispose      (GObject      *object);

static GObjectClass *parent_class = NULL;

KZ_OBJECT_GET_TYPE(kz_navi, "KzNavi", KzNavi,
                   kz_navi_class_init, kz_navi_init,
                   G_TYPE_OBJECT)

static void
kz_navi_class_init (KzNaviClass *klass)
{
	GObjectClass *object_class;

	parent_class = g_type_class_peek_parent(klass);
	object_class = (GObjectClass *)klass;

	object_class->dispose = kz_navi_dispose;
}

static void
kz_navi_init (KzNavi *navi)
{
}

KzNavi *
kz_navi_new (void)
{
	return kz_navi_new_with_info(NULL, NULL, NULL, NULL);
}

KzNavi *
kz_navi_new_with_info (const gchar *name, const gchar *uri,
                       const gchar *title, const gchar *type)
{
	KzNavi *navi;

	navi = g_object_new(KZ_TYPE_NAVI, NULL);

	navi->name = g_strdup(name);
	navi->uri = g_strdup(uri);
	navi->title = g_strdup(title);
	navi->type = g_strdup(type);
	
	return navi;
}

static void
kz_navi_dispose (GObject *object)
{
	KzNavi *navi = KZ_NAVI(object);

	g_free(navi->name);
	g_free(navi->uri);
	g_free(navi->title);
	g_free(navi->type);
	
	navi->name = NULL;
	navi->uri = NULL;
	navi->title = NULL;
	navi->type = NULL;
	
	if (G_OBJECT_CLASS (parent_class)->dispose)
		(*G_OBJECT_CLASS (parent_class)->dispose) (object);
}

void
kz_navi_add_bookmark (KzNavi *navi)
{
	KzBookmark *folder, *bookmark, *sibling = NULL;
	KzBookmark *file;
	GList *bars;
	const gchar *title, *uri;

	g_return_if_fail(navi);
	g_return_if_fail(navi->uri);

	bars = kz_bookmark_get_children(kz_bookmarks->bookmark_bars);
	g_return_if_fail(bars);
	
	folder = bars->data;
	g_list_free(bars);
	
	if (!kz_bookmark_is_folder(folder))
	{
		sibling = folder;
		folder = kz_bookmark_get_parent(folder);
		g_return_if_fail(KZ_IS_BOOKMARK(folder));
	}

	title = navi->title ? navi->title : _("Feed");
	uri   = navi->uri;

	bookmark = KZ_BOOKMARK(kz_bookmark_file_new(uri, title, NULL));
	/* FIXME! show dialog */
	if (sibling)
		kz_bookmark_insert_before(folder, bookmark, sibling);
	else
		kz_bookmark_append(folder, bookmark);
	
	if (KZ_IS_BOOKMARK_FILE(folder))
		file = folder;
	else
		file = kz_bookmark_get_parent_file(folder);
	
	kz_bookmark_file_save(KZ_BOOKMARK_FILE(file));

	g_object_unref(G_OBJECT(bookmark));
}
