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

/*
 *  Copyright (C) 2004 Hidetaka Iwai
 *
 *  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.
 *
 *  $Id: kz-proxy-menu.c 1930 2005-02-13 13:20:37Z ikezoe $
 */

#include "kz-proxy-menu.h"

#include <glib/gi18n.h>
#include "kazehakase.h"

#include "kz-proxy-item.h"
#include "utils.h"

#define KZ_PROXY_MENU_PROXY_KEY    "KzProxyMenu::Proxy"

static void       cb_proxy_menuitem_activate     (GtkWidget      *menuitem,
						  KzWindow       *kz);

void
kz_proxy_menu_append_menuitems (GtkMenuShell *shell, KzWindow *kz)
{
	GSList *group = NULL;
	GList *node, *list;
	gchar proxy_name[1024];
	gboolean ret;

	g_return_if_fail(GTK_IS_MENU_SHELL(shell));

	ret = KZ_CONF_GET("Global", "proxy_name", proxy_name, STRING);

	list = kz_proxy_get_list();
	for (node = list; node; node = g_list_next(node))
	{
		KzProxyItem *item = KZ_PROXY_ITEM(node->data);
		GtkWidget  *menuitem = gtk_radio_menu_item_new_with_label (group,item->name);

		if (ret && !strcmp(proxy_name, item->name))
		{
			gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (menuitem),
							TRUE);
		}

		group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (menuitem));

		g_object_set_data (G_OBJECT (menuitem), KZ_PROXY_MENU_PROXY_KEY,
				   (gchar*)item->name);

		g_signal_connect (menuitem, "activate",
				  G_CALLBACK (cb_proxy_menuitem_activate), kz);

		gtk_menu_shell_append (shell, menuitem);
		gtk_widget_show (menuitem);

	}
	g_list_free(list);
}

void
kz_proxy_menu_remove_menuitems (GtkMenuShell *shell, KzWindow *kz)
{
	GList *list, *node;

	list = g_list_copy(shell->children);

	for (node = list; node; node = g_list_next(node))
	{
		GtkWidget *menuitem = node->data;
		g_signal_handlers_disconnect_by_func(menuitem,
						     G_CALLBACK(cb_proxy_menuitem_activate),
						     kz);
		gtk_widget_destroy(menuitem);
	}
	g_list_free(list);
}

static void
cb_proxy_menuitem_activate (GtkWidget *menuitem, KzWindow *kz)
{
	if (GTK_CHECK_MENU_ITEM(menuitem)->active)
	{
		const gchar* proxy_name = g_object_get_data (G_OBJECT(menuitem),
							     KZ_PROXY_MENU_PROXY_KEY);
		KZ_CONF_SET_STR("Global", "proxy_name", proxy_name);
	}
}
