########################################################################
#
#  Copyright (C) 2009, CZ.NIC, z.s.p.o.
# 
#  This file is part of dnstester.
#
#  dnstester 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 3 of the License, or
#  (at your option) any later version.
#
#  dnstester 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, see <http://www.gnu.org/licenses/>.
#
########################################################################

import sys
import config, messages, combo
import gtk
import locale

language = config.default_language
lang_translations = {
    'en_US' : 'en', 'cs_CZ': 'cz', 'hu_HU': 'hu',
    'English_United States': 'en', 'Czech_Czech Republic': 'cz', 'Hungarian_Hungary': 'hu',
    }
bindings = {}


def languages():
    return lang_translations.values()


def set_label(widget, tag):
    if isinstance(widget, combo.LangCombo):
        widget.refill()
    elif isinstance(widget, gtk.Widget):
        widget.set_label(messages.messages[language][tag])
    else:
        print 'warning: invalid widget type'


def bind(widget, tag):
    bindings[widget] = tag
    set_label(widget, tag)


def setup_language(lang):
    language = lang
    
    for (widget, tag) in bindings.items(): set_label(widget, tag)


def get_string(tag):
    if tag.startswith('@@'):
        return tag[2:]
    else:
        return messages.messages[language][tag]


def get_default_locale_language():
    try:
        locale.setlocale(locale.LC_ALL, '')
        if hasattr(locale, 'LC_MESSAGES'):
            l = locale.getlocale(locale.LC_MESSAGES)
        else:
            l = locale.getlocale()

        if l[0] == None:
            l = locale.getdefaultlocale()

        return l[0]
    except:
        print 'error detecting language'
        return None


def set_default_language():

    global language

    # command line has higher priority
    for l in lang_translations.values():
        if '--language=' + l in sys.argv:
            language = l
            return
    
    code = get_default_locale_language()
    if lang_translations.has_key(code):
        language = lang_translations[code]
    else:
        print ('unsupported language code %s' % code)
        language = lang_translations['en_US']
