# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.

"""
i18n related functions
"""

__maintainer__ = 'Philippe Normand <philippe@fluendo.com>'

from elisa.core import log
from elisa.extern import msgfmt
import os
import sys
import glob
import gettext
import locale
import pkg_resources
import platform

def compile_po_files(domain, directory, dest_directory, announce_func=None):
    announce_func = announce_func or (lambda msg: sys.stdout.write("%s\n" % msg))

    announce_func("Compiling po files in %r directory for domain %s" % (directory, domain))

    package_path = os.path.dirname(dest_directory).replace(os.path.sep, '.')
    basename = os.path.basename(dest_directory)
    mo_files = {package_path: [os.path.join(basename, '*',
                                           'LC_MESSAGES', '*.mo')]}

    pattern = '%s/*.po' % directory
    for filename in glob.glob(pattern):
        announce_func("Trying to compile %r" % filename)
        basename, ext = os.path.splitext(filename)
        lang = os.path.basename(basename)
        src = filename
        destdir = os.path.join(dest_directory, lang, 'LC_MESSAGES')
        dest = os.path.join(destdir, "%s.mo" % domain)
        if not os.path.exists(dest):
            if not os.path.exists(destdir):
                try:
                    os.makedirs(destdir)
                except OSError, e:
                    announce_func("Could not make directory %r: %r. " \
                                  "Skipped %s." % (destdir,e,dst))
                else:
                    announce_func("Compiling %s to %s" % (src, dest))
                    msgfmt.make(src, dest)

        else:
            src_mtime = os.stat(src)[8]
            dest_mtime = os.stat(dest)[8]
            if src_mtime > dest_mtime:
                announce_func("Compiling %s to %s" % (src, dest))
                msgfmt.make(src, dest)
            else:
                announce_func("Skipping already compiled %r" % dest)

    return mo_files

def get_current_locale():
    if platform.system().lower() == 'windows':
        # windows hack for locale setting
        default_lang, default_enc = locale.getdefaultlocale()
        lang = os.getenv('LANG')
        if lang is None:
            lang = default_lang
            os.environ['LANG'] = lang
        current_locale = lang
    else:
        current_locale = locale.getdefaultlocale()[0]
        if current_locale is None:
            current_locale = os.getenv('LANG')

    return current_locale

def install_translation(plugin_name, plural = False):
    log_category = 'i18n'
    domain = 'elisa-plugin-%s' % plugin_name
    i18n_dir = pkg_resources.resource_filename('elisa.plugins.%s' % plugin_name,
                                               'i18n')

    current_locale = get_current_locale()
    try:
        fallback_locale = current_locale.split('_')[0]
        t = gettext.translation(domain, i18n_dir, languages=[current_locale, fallback_locale])
        translator = t.ugettext
        translator_plural = t.ungettext
    except (AttributeError, IOError), error:
        # if the locale couldn't be determined or there's no translation for it
        translator = lambda string: string
        translator_plural = lambda singular, plural, num: num == 1 and singular or plural
        log.info(log_category,"Translation not found for locale %r in plugin %r",
                 current_locale, plugin_name)
    else:
        log.info(log_category, "Loaded translation for locale %r in plugin %r",
                 current_locale, plugin_name)
    if plural:
        return translator, translator_plural
    else:
        return translator
