/* -*- 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 "prefs_lang.h"

#include <string.h>

#include "kz-dlist.h"
#include "mozilla-prefs.h"
#include "utils/intl.h"


#define DATA_KEY "KzPrefsLang::info"


static GtkWidget     *prefs_lang_create          (void);
static void           prefs_lang_response        (GtkWidget *widget,
						  gint       response);


static KzPrefsWinPageEntry prefs_entry =
{
	path:            N_("/Language"),
	priority_hint:   0,
	create:          prefs_lang_create,
	response:        prefs_lang_response,
};


typedef struct _KzPrefsLang
{
	GtkWidget     *main_vbox;
	GtkWidget     *option_menu_lang;
	GtkWidget     *option_menu_autodetect;
	GtkWidget     *lang_dlist;
	gboolean       enabled_list_updated;
} KzPrefsLang;


typedef enum {
        LG_ARABIC,
        LG_BALTIC,
        LG_CENTRAL_EUROPEAN,
        LG_CHINESE,
        LG_CYRILLIC,
        LG_GREEK,
        LG_HEBREW,
        LG_INDIAN,
        LG_JAPANESE,
        LG_KOREAN,
        LG_TURKISH,
        LG_UNICODE,
        LG_VIETNAMESE,
        LG_WESTERN,
        LG_OTHER
} LanguageGroup;


/*
 *  These arrays are picked from epiphany-0.7 (src/prefs-diarlog.c).
 *  Copyright (C) 2000, 2001, 2002 Marco Pesenti Gritti
 */
static const
struct
{
	char *name;
	char *code;
	LanguageGroup group;
}
languages [] =
{
	{ N_("Arabic (IBM-864)"),                  "IBM864",                LG_ARABIC },
	{ N_("Arabic (IBM-864-I)"),                "IBM864i",               LG_ARABIC },
	{ N_("Arabic (ISO-8859-6)"),               "ISO-8859-6",            LG_ARABIC },
	{ N_("Arabic (ISO-8859-6-E)"),             "ISO-8859-6-E",          LG_ARABIC },
	{ N_("Arabic (ISO-8859-6-I)"),             "ISO-8859-6-I",          LG_ARABIC },
	{ N_("Arabic (MacArabic)"),                "x-mac-arabic",          LG_ARABIC },
	{ N_("Arabic (Windows-1256)"),             "windows-1256",          LG_ARABIC },
	{ N_("Armenian (ARMSCII-8)"),              "armscii-8",             LG_OTHER },
	{ N_("Baltic (ISO-8859-13)"),              "ISO-8859-13",           LG_BALTIC },
	{ N_("Baltic (ISO-8859-4)"),               "ISO-8859-4",            LG_BALTIC },
	{ N_("Baltic (Windows-1257)"),             "windows-1257",          LG_BALTIC },
	{ N_("Celtic (ISO-8859-14)"),              "ISO-8859-14",           LG_OTHER },
	{ N_("Central European (IBM-852)"),        "IBM852",                LG_CENTRAL_EUROPEAN },
	{ N_("Central European (ISO-8859-2)"),     "ISO-8859-2",            LG_CENTRAL_EUROPEAN },
	{ N_("Central European (MacCE)"),          "x-mac-ce",              LG_CENTRAL_EUROPEAN },
	{ N_("Central European (Windows-1250)"),   "windows-1250",          LG_CENTRAL_EUROPEAN },
	{ N_("Chinese Simplified (GB18030)"),      "gb18030",               LG_CHINESE },
	{ N_("Chinese Simplified (GB2312)"),       "GB2312",                LG_CHINESE },
	{ N_("Chinese Simplified (GBK)"),          "x-gbk",                 LG_CHINESE },
	{ N_("Chinese Simplified (HZ)"),           "HZ-GB-2312",	    LG_CHINESE },
	{ N_("Chinese Simplified (ISO-2022-CN)"),  "ISO-2022-CN",           LG_CHINESE },
	{ N_("Chinese Simplified (Windows-936)"),  "windows-936",           LG_CHINESE },
	{ N_("Chinese Traditional (Big5)"),        "Big5",                  LG_CHINESE },
	{ N_("Chinese Traditional (Big5-HKSCS)"),  "Big5-HKSCS",	    LG_CHINESE },
	{ N_("Chinese Traditional (EUC-TW)"),      "x-euc-tw",              LG_CHINESE },
	{ N_("Croatian (Mac Croatian)"),           "x-mac-croatian",        LG_CENTRAL_EUROPEAN },
	{ N_("Cyrillic (IBM-855)"),                "IBM855",                LG_CYRILLIC },
	{ N_("Cyrillic (ISO-8859-5)"),             "ISO-8859-5",	    LG_CYRILLIC },
	{ N_("Cyrillic (ISO-IR-111)"),             "ISO-IR-111",            LG_CYRILLIC },
	{ N_("Cyrillic (KOI8-R)"),                 "KOI8-R",                LG_CYRILLIC },
	{ N_("Cyrillic (MacCyrillic)"),            "x-mac-cyrillic",        LG_CYRILLIC },
	{ N_("Cyrillic (Windows-1251)"),           "windows-1251",          LG_CYRILLIC },
	{ N_("Cyrillic/Russian (CP-866)"),         "IBM866",                LG_CYRILLIC },
	{ N_("Cyrillic/Ukrainian (KOI8-U)"),       "KOI8-U",                LG_CYRILLIC },
	{ N_("Cyrillic/Ukrainian (Mac Ukrainian)"),"x-mac-ukrainian",       LG_CYRILLIC },
	{ N_("English (US-ASCII)"),                "us-ascii",              LG_WESTERN },
	{ N_("Farsi (MacFarsi)"),                  "x-mac-farsi",           LG_OTHER },
	{ N_("Georgian (GEOSTD8)"),                "geostd8",               LG_OTHER },
	{ N_("Greek (ISO-8859-7)"),                "ISO-8859-7",            LG_GREEK },
	{ N_("Greek (MacGreek)"),                  "x-mac-greek",           LG_GREEK },
	{ N_("Greek (Windows-1253)"),              "windows-1253",          LG_GREEK },
	{ N_("Gujarati (MacGujarati)"),            "x-mac-gujarati",        LG_INDIAN },
	{ N_("Gurmukhi (Mac Gurmukhi)"),           "x-mac-gurmukhi",        LG_INDIAN },
	{ N_("Hebrew (IBM-862)"),                  "IBM862",                LG_HEBREW },
	{ N_("Hebrew (ISO-8859-8-E)"),             "ISO-8859-8-E",          LG_HEBREW },
	{ N_("Hebrew (ISO-8859-8-I)"),             "ISO-8859-8-I",          LG_HEBREW },
	{ N_("Hebrew (MacHebrew)"),                "x-mac-hebrew",          LG_HEBREW },
	{ N_("Hebrew (Windows-1255)"),             "windows-1255",          LG_HEBREW },
	{ N_("Hindi (Mac Devanagari)"),            "x-mac-devanagari",      LG_INDIAN },
	{ N_("Icelandic (MacIcelandic)"),          "x-mac-icelandic",       LG_OTHER },
	{ N_("Japanese (EUC-JP)"),                 "EUC-JP",                LG_JAPANESE },
	{ N_("Japanese (ISO-2022-JP)"),            "ISO-2022-JP",           LG_JAPANESE },
	{ N_("Japanese (Shift_JIS)"),              "Shift_JIS",             LG_JAPANESE },
	{ N_("Korean (EUC-KR)"),                   "EUC-KR",                LG_KOREAN },
	{ N_("Korean (ISO-2022-KR)"),              "ISO-2022-KR",           LG_KOREAN },
	{ N_("Korean (JOHAB)"),                    "x-johab",               LG_KOREAN },
	{ N_("Korean (UHC)"),                      "x-windows-949",         LG_KOREAN },
	{ N_("Nordic (ISO-8859-10)"),              "ISO-8859-10",           LG_OTHER },
	{ N_("Romanian (MacRomanian)"),            "x-mac-romanian",        LG_OTHER },
	{ N_("Romanian (ISO-8859-16)"),            "ISO-8859-16",           LG_OTHER },
	{ N_("South European (ISO-8859-3)"),       "ISO-8859-3",            LG_OTHER },
	{ N_("Thai (TIS-620)"),                    "TIS-620",               LG_OTHER },
	{ N_("Turkish (IBM-857)"),                 "IBM857",                LG_TURKISH },
	{ N_("Turkish (ISO-8859-9)"),              "ISO-8859-9",            LG_TURKISH },
	{ N_("Turkish (MacTurkish)"),              "x-mac-turkish",         LG_TURKISH },
	{ N_("Turkish (Windows-1254)"),            "windows-1254",          LG_TURKISH },
	{ N_("Unicode (UTF-7)"),                   "UTF-7",                 LG_UNICODE },
	{ N_("Unicode (UTF-8)"),                   "UTF-8",                 LG_UNICODE },
	{ N_("Unicode (UTF-16BE)"),                "UTF-16BE",              LG_UNICODE },
	{ N_("Unicode (UTF-16LE)"),                "UTF-16LE",              LG_UNICODE },
	{ N_("Unicode (UTF-32BE)"),                "UTF-32BE",              LG_UNICODE },
	{ N_("Unicode (UTF-32LE)"),                "UTF-32LE",              LG_UNICODE },
	{ N_("User Defined"),                      "x-user-defined",        LG_OTHER },
	{ N_("Vietnamese (TCVN)"),                 "x-viet-tcvn5712",       LG_VIETNAMESE },
	{ N_("Vietnamese (VISCII)"),               "VISCII",                LG_VIETNAMESE },
	{ N_("Vietnamese (VPS)"),                  "x-viet-vps",            LG_VIETNAMESE },
	{ N_("Vietnamese (Windows-1258)"),         "windows-1258",          LG_VIETNAMESE },
	{ N_("Visual Hebrew (ISO-8859-8)"),        "ISO-8859-8",            LG_HEBREW },
	{ N_("Western (IBM-850)"),                 "IBM850",                LG_WESTERN },
	{ N_("Western (ISO-8859-1)"),              "ISO-8859-1",            LG_WESTERN },
	{ N_("Western (ISO-8859-15)"),             "ISO-8859-15",           LG_WESTERN },
	{ N_("Western (MacRoman)"),                "x-mac-roman",           LG_WESTERN },
	{ N_("Western (Windows-1252)"),            "windows-1252",          LG_WESTERN },
	/* encodings without translatable names */
	{ "T.61-8bit",                             "T.61-8bit",             LG_OTHER },
	{ "x-imap4-modified-utf7",                 "x-imap4-modified-utf7", LG_UNICODE },
	{ "x-u-escaped",                           "x-u-escaped",           LG_OTHER }
};
static guint n_languages = G_N_ELEMENTS (languages);

static const
struct
{
	char *name;
	char *code;
}
accept_languages [] =
{
	/**
	 * please translate like this: "<your language> (System setting)"
	 * Examples:
	 * "de"    translation: "Deutsch (Systemeinstellung)"
	 * "en_AU" translation: "English, Australia (System setting)" or
	 *                      "Australian English (System setting)"
	 */ 
	/* { N_("System language"), "system" }, */
	{ N_("Afrikaans"), "ak" },
	{ N_("Albanian"), "sq" },
	{ N_("Arabic"), "ar" },
	{ N_("Azerbaijani"), "az" },
	{ N_("Basque"), "eu" },
	{ N_("Breton"), "br" },
	{ N_("Bulgarian"), "bg" },
	{ N_("Byelorussian"), "be" },
	{ N_("Catalan"), "ca" },
	{ N_("Simplified Chinese"), "zh-cn" },
	{ N_("Traditional Chinese"), "zh-tw" },
	{ N_("Chinese"), "zh" },
	{ N_("Croatian"), "hr" },
	{ N_("Czech"), "cs" },
	{ N_("Danish"), "da" },
	{ N_("Dutch"), "nl" },
	{ N_("English"), "en" },
	{ N_("Esperanto"), "eo" },
	{ N_("Estonian"), "et" },
	{ N_("Faeroese"), "fo" },
	{ N_("Finnish"), "fi" },
	{ N_("French"), "fr" },
	{ N_("Galician"), "gl" },
	{ N_("German"), "de" },
	{ N_("Greek"), "el" },
	{ N_("Hebrew"), "he" },
	{ N_("Hungarian"), "hu" },
	{ N_("Icelandic"), "is" },
	{ N_("Indonesian"), "id" },
	{ N_("Irish"), "ga" },
	{ N_("Italian"), "it" },
	{ N_("Japanese"), "ja" },
	{ N_("Korean"), "ko" },
	{ N_("Latvian"), "lv" },
	{ N_("Lithuanian"), "lt" },
	{ N_("Macedonian"), "mk" },
	{ N_("Malay"), "ms" },
	{ N_("Norwegian/Nynorsk"), "nn" },
	{ N_("Norwegian/Bokmal"), "nb" },
	{ N_("Norwegian"), "no" },
	{ N_("Polish"), "pl" },
	{ N_("Portuguese"), "pt" },
	{ N_("Portuguese of Brazil"), "pt-br" },
	{ N_("Romanian"), "ro" },
	{ N_("Russian"), "ru" },
	{ N_("Scottish"), "gd" },
	{ N_("Serbian"), "sr" },
	{ N_("Slovak"), "sk" },
	{ N_("Slovenian"), "sl" },
	{ N_("Spanish"), "es" },
	{ N_("Swedish"), "sv" },
	{ N_("Tamil"), "ta" },
	{ N_("Turkish"), "tr" },
	{ N_("Ukrainian"), "uk" },
	{ N_("Vietnamese"), "vi" },
	{ N_("Walloon"), "wa" }
};
static guint n_accept_languages = G_N_ELEMENTS (accept_languages);


typedef struct
{
	gchar *title;
	gchar *name;
} EncodingAutodetectorInfo;

static EncodingAutodetectorInfo encoding_autodetectors[] =
{
	{ N_("Off"),			"" },
	{ N_("Chinese"),		"zh_parallel_state_machine" },
	{ N_("East asian"),		"cjk_parallel_state_machine" },
	{ N_("Japanese"),		"ja_parallel_state_machine" },
	{ N_("Korean"),			"ko_parallel_state_machine" },
	{ N_("Russian"),		"ruprob" },
	{ N_("Simplified Chinese"),	"zhcn_parallel_state_machine" },
	{ N_("Traditional Chinese"),	"zhtw_parallel_state_machine" },
	{ N_("Ukrainian"),		"ukprob" }
};
static guint n_encoding_autodetectors = G_N_ELEMENTS (encoding_autodetectors);


#define CREATE_MENU(menu, array, n_array, field)                               \
{                                                                              \
	gint i;                                                                \
                                                                               \
	menu = gtk_menu_new ();                                                \
                                                                               \
	for (i = 0; i < n_array; i++)                                          \
	{                                                                      \
		GtkWidget *item;                                               \
                                                                               \
		item = gtk_menu_item_new_with_label (_(array[i].field));       \
		gtk_menu_shell_append (GTK_MENU_SHELL(menu), item);            \
		gtk_widget_show (item);                                        \
	}                                                                      \
}


#define SET_DEFAULT_HISTORY(menu, key, array, n_array, field)                  \
{                                                                              \
	gchar *str;                                                            \
	gint i;                                                                \
                                                                               \
	if (mozilla_prefs_get_string(key, &str))                               \
	{                                                                      \
		for (i = 0; i < n_array; i++)                                  \
		{                                                              \
			if (!strcmp(str, array[i].field))                      \
			{                                                      \
				gtk_option_menu_set_history(GTK_OPTION_MENU(menu), i); \
				break;                                         \
			}                                                      \
		}                                                              \
		g_free(str);                                                   \
	}                                                                      \
}


static void
prefs_lang_destroy (gpointer data)
{
	KzPrefsLang *prefsui = data;

	g_free(prefsui);
}


static void
cb_enabled_list_updated (KzDList *dlist, KzPrefsLang *prefsui)
{
	prefsui->enabled_list_updated = TRUE;
}


static GtkWidget *
prefs_lang_create (void)
{
	KzPrefsLang *prefsui = g_new0(KzPrefsLang, 1);
	GtkWidget *main_vbox, *vbox, *hbox;
	GtkWidget *label, *table, *option_menu, *menu, *frame,*dlist;
	gchar *str, **langs;
	gint i;

	prefsui->enabled_list_updated = FALSE;

	main_vbox = gtk_vbox_new (FALSE, 0);
	prefsui->main_vbox = main_vbox;
	g_object_set_data_full (G_OBJECT(main_vbox),
				DATA_KEY, prefsui,
				(GDestroyNotify) prefs_lang_destroy);

	label = kz_prefs_ui_utils_create_title(_("Language"));
	gtk_box_pack_start(GTK_BOX(main_vbox), label,
			   FALSE, FALSE, 0);
	gtk_widget_show(label);

	vbox = gtk_vbox_new (FALSE, 0);
	gtk_container_set_border_width(GTK_CONTAINER(vbox), 5);
	gtk_box_pack_start(GTK_BOX(main_vbox), vbox,
			   TRUE, TRUE, 0);
	gtk_widget_show(vbox);

	table = gtk_table_new(2, 2, FALSE);
	gtk_box_pack_start(GTK_BOX(vbox), table,
			   FALSE, FALSE, 0);
	gtk_widget_show(table);

	/*
	 *  Default Encoding
	 */
	frame = gtk_frame_new(NULL);
	gtk_frame_set_label_align(GTK_FRAME(frame), 0.03, 0.5);
	gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 5);
	gtk_widget_show(frame);

	label = gtk_label_new_with_mnemonic(_("_Default Encoding"));
	gtk_label_set_use_underline(GTK_LABEL(label), TRUE);
	gtk_frame_set_label_widget(GTK_FRAME(frame), label);
	gtk_widget_show(label);

	hbox = gtk_hbox_new(FALSE, 0);
	gtk_container_set_border_width(GTK_CONTAINER(hbox), 5);
	gtk_container_add(GTK_CONTAINER(frame), hbox);
	gtk_widget_show(hbox);

	option_menu = gtk_option_menu_new();
	prefsui->option_menu_lang = option_menu;
	gtk_label_set_mnemonic_widget(GTK_LABEL(label), option_menu);
	gtk_box_pack_start(GTK_BOX(hbox), option_menu, FALSE, FALSE, 0);
	gtk_widget_show(option_menu);

	CREATE_MENU(menu, languages, n_languages, name);
	gtk_option_menu_set_menu (GTK_OPTION_MENU(option_menu), menu);
	SET_DEFAULT_HISTORY(option_menu, "intl.charset.default",
			    languages, n_languages, code);
	gtk_widget_show(menu);

	/*
	 *  Auto detect
	 */
	frame = gtk_frame_new(NULL);
	gtk_frame_set_label_align(GTK_FRAME(frame), 0.03, 0.5);
	gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 5);
	gtk_widget_show(frame);

	label = gtk_label_new_with_mnemonic(_("A_utodetect Encoding"));
	gtk_frame_set_label_widget(GTK_FRAME(frame), label);
	gtk_widget_show(label);

	hbox = gtk_hbox_new(FALSE, 0);
	gtk_container_set_border_width(GTK_CONTAINER(hbox), 5);
	gtk_container_add(GTK_CONTAINER(frame), hbox);
	gtk_widget_show(hbox);

	option_menu = gtk_option_menu_new();
	prefsui->option_menu_autodetect = option_menu;
	gtk_label_set_mnemonic_widget(GTK_LABEL(label), option_menu);
	gtk_box_pack_start(GTK_BOX(hbox), option_menu, FALSE, FALSE, 0);
	gtk_widget_show(option_menu);

	CREATE_MENU(menu, encoding_autodetectors, n_encoding_autodetectors, title);
	gtk_option_menu_set_menu (GTK_OPTION_MENU(option_menu), menu);
	SET_DEFAULT_HISTORY(option_menu, "intl.charset.detector",
			    encoding_autodetectors, n_encoding_autodetectors,
			    name);
	gtk_widget_show(menu);

	/*
	 *  Accept Language
	 */
	frame = gtk_frame_new(_("Accept Language"));
	gtk_frame_set_label_align(GTK_FRAME(frame), 0.03, 0.5);
	gtk_box_pack_start(GTK_BOX(vbox), frame, TRUE, TRUE, 5);
	gtk_widget_show(frame);

	dlist = kz_dlist_new(_("Available Languages"),
			     _("Enabled Languages"));
	prefsui->lang_dlist = dlist;
	gtk_container_set_border_width(GTK_CONTAINER(dlist), 5);
	gtk_container_add(GTK_CONTAINER(frame), dlist);
	gtk_widget_show(dlist);

	for (i = 0; i < n_accept_languages; i++)
	{
		const gchar *name = accept_languages[i].name;
		const gchar *code = accept_languages[i].code;

		kz_dlist_append_available_item(KZ_DLIST(dlist), name, code);
	}

	mozilla_prefs_get_string("intl.accept_languages", &str);
	langs = g_strsplit(str, ",", -1);
	if (langs)
	{
		for (i = 0; langs[i]; i++)
		{
			g_strstrip(langs[i]);
			kz_dlist_column_add_by_id(KZ_DLIST(dlist), langs[i]);
		}
		g_strfreev(langs);
	}
	g_signal_connect(G_OBJECT(dlist), "enabled-list-updated",
			 G_CALLBACK(cb_enabled_list_updated), prefsui);

	return main_vbox;
}


#define GET_HISTORY(option_menu) \
	(gtk_option_menu_get_history(GTK_OPTION_MENU(option_menu)))


static void
prefs_lang_response (GtkWidget *widget, gint response)
{
	KzPrefsLang *prefsui = g_object_get_data(G_OBJECT(widget), DATA_KEY);
	gint i, j;

	g_return_if_fail(prefsui);

	switch (response) {
	case GTK_RESPONSE_ACCEPT:
	case GTK_RESPONSE_APPLY:
		i = GET_HISTORY(prefsui->option_menu_lang);
		j = GET_HISTORY(prefsui->option_menu_autodetect);
		if (i >= 0 && i < n_languages) {
			mozilla_prefs_set_string("intl.charset.default",
						 languages[i].code);
		}
		if (j >= 0 && j < n_encoding_autodetectors) {
			if (mozilla_prefs_set_string("intl.charset.detector",
						     encoding_autodetectors[j].name));
		}

		if (prefsui->enabled_list_updated)
		{
			gint i, num = kz_dlist_get_n_enabled_items(KZ_DLIST(prefsui->lang_dlist));
			gchar *langs = strdup("");

			for (i = 0; i < num; i++)
			{
				gchar *lang, *tmp;
				lang = kz_dlist_get_enabled_id(KZ_DLIST(prefsui->lang_dlist), i);
				tmp = langs;
				if (i == 0)
					langs = g_strconcat(langs, lang, NULL);
				else
					langs = g_strconcat(langs, ",", lang, NULL);
				g_free(tmp);
			}
			mozilla_prefs_set_string("intl.accept_languages", langs);
			g_free(langs);
			prefsui->enabled_list_updated = FALSE;
		}
		break;
	case GTK_RESPONSE_REJECT:
		break;
	default:
		break;
	}
}


KzPrefsWinPageEntry *
prefs_lang_get_entry (gint idx)
{
	if (idx == 0)
		return &prefs_entry;
	else
		return NULL;
}
