# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Lukáš Lalinský <lalinsky@gmail.com>
# Copyright (C) 2007,2009 Alexander Belchenko <bialix@ukr.net>
#
# 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
# of the License, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

"""I18N and L10N support"""

import gettext as _gettext
import os
import sys

_null_translation = _gettext.NullTranslations()
_translation = _null_translation


def gettext(s):
    return _translation.ugettext(s)

def ngettext(s, p, n):
    return _translation.ungettext(s, p, n)

def N_(s):
    return s


def install():
    global _translation
    get_current_locale()
    _translation = _gettext.translation('explorer', localedir=_get_locale_dir(), fallback=True)


def uninstall():
    global _translation
    _translation = _null_translation


def _get_locale_dir():
    localedir = os.path.join(os.path.realpath(os.path.dirname(__file__)), '..', 'locale')
    if sys.platform.startswith('linux'):
        if not os.access(localedir, os.R_OK | os.X_OK):
            localedir = '/usr/share/locale'
    return localedir


def _check_win32_locale():
    for i in ('LANGUAGE','LC_ALL','LC_MESSAGES','LANG'):
        if os.environ.get(i):
            break
    else:
        lang = None
        import locale
        try:
            import ctypes
        except ImportError:
            # use only user's default locale
            lang = locale.getdefaultlocale()[0]
        else:
            # using ctypes to determine all locales
            lcid_user = ctypes.windll.kernel32.GetUserDefaultLCID()
            lcid_system = ctypes.windll.kernel32.GetSystemDefaultLCID()
            if lcid_user != lcid_system:
                lcid = [lcid_user, lcid_system]
            else:
                lcid = [lcid_user]
            lang = [locale.windows_locale.get(i) for i in lcid]
            lang = ':'.join([i for i in lang if i])
        # set lang code for gettext
        if lang:
            os.environ['LANGUAGE'] = lang


def get_current_locale():
    from bzrlib import config
    lang = config.GlobalConfig().get_user_option('language')
    if lang:
        os.environ['LANGUAGE'] = lang
        return lang
    if sys.platform == 'win32':
        _check_win32_locale()
    for i in ('LANGUAGE','LC_ALL','LC_MESSAGES','LANG'):
        lang = os.environ.get(i)
        if lang:
            return lang
    return None


def save_default_language(language):
    from bzrlib import config
    config.GlobalConfig().set_user_option('language', language)


def get_available_translations():
    try:
        result = []
        for lang in os.listdir(_get_locale_dir()):
            result.append(lang)
        return result
    except (OSError, IOError):
        return []


# special zzz translation for debugging i18n stuff
class _ZzzTranslations(object):

    def __init__(self):
        pass

    def zzz(self, s):
        return 'zz{{%s}}' % s

    def ugettext(self, s):
        return self.zzz(_null_translation.ugettext(s))

    def ungettext(self, s, p, n):
        return self.zzz(_null_translation.ungettext(s, p, n))


def install_zzz():
    global _translation
    _translation = _ZzzTranslations()


# XXX add more language codes (should match set of po files)
LANGUAGES = dict(
    ar=N_('Arabic'),
    ca=N_('Catalan'),
    cs=N_('Czech'),
    da=N_('Danish'),
    de=N_('German'),
    el=N_('Greek'),
    en=N_('English'),
    en_AU=N_('English (Australia)'),
    en_CA=N_('English (Canada)'),
    en_GB=N_('English (United Kingdom)'),
    es=N_('Spanish'),
    et=N_('Estonian'),
    eu=N_('Basque'),
    fi=N_('Finnish'),
    fr=N_('French'),
    gl=N_('Galician'),
    he=N_('Hebrew'),
    hu=N_('Hungarian'),
    id=N_('Indonesian'),
    it=N_('Italian'),
    ja=N_('Japanese'),
    lo=N_('Lao'),
    lt=N_('Lithuanian'),
    nl=N_('Dutch'),
    oc=N_('Occitan (post 1500)'),
    pl=N_('Polish'),
    pt=N_("Portuguese"),
    pt_BR=N_('Brazilian Portuguese'),
    ru=N_('Russian'),
    sk=N_('Slovak'),
    sl=N_('Slovenian'),
    sr=N_('Serbian'),
    sv=N_('Swedish'),
    th=N_('Thai'),
    tr=N_('Turkish'),
    ug=N_('Uyghur'),
    uk=N_('Ukrainian'),
    zh_CN=N_('Chinese (Simplified)'),
    zh_TW=N_('Chinese (Traditional)'),
    )
