# -*- coding: utf-8 -*-

"""module handling translations

Note: all translation files have to follow the convention name_localename.qm

"""


import os
from PyQt4 import QtCore, QtGui
#***************************************************************
#
#***************************************************************
SZ_APP = "chartables"
DEFAULT_LOCALE = "en"

# for fast lookups. Keep in sync with CT_Language() + sorted
LOCALE_NAMES = ('de', "en", "fr", "pt_BR", "ru")

#***************************************************************
#
#***************************************************************
class CT_Language(QtCore.QObject):
    """class wrapping locale names names"""

    def trUtf8(self, what):
        def translate():
            return QtCore.QObject.trUtf8(self, what)
        return translate


    def __init__(self):
        QtCore.QObject.__init__(self)

        self.LANG_EN = self.trUtf8("English")
        self.LANG_DE = self.trUtf8("German")
        self.LANG_FR = self.trUtf8("French")
        self.LANG_RU = self.trUtf8("Russian")
        self.LANG_PT_BR = self.trUtf8("Portuguese (Brazilian)")



#***************************************************************
#
#***************************************************************
class Language(object):
    """class handling languages for the package"""

    def __init__(self):
        """constructor"""

        # do a lazy initialize here
        self.__languageStrings = None
        self.__translator = None
        self.__defaultLocale = DEFAULT_LOCALE


    def hasLocaleName(self, localeName):
        """checks if a locale corrosponding to the specified locale name is available"""
        # mimic the Qt behavior
        haveIt = localeName in LOCALE_NAMES
        while not haveIt and '_' in localeName:
            localeName = '_'.join(localeName.split('_')[:-1])
            haveIt = localeName in LOCALE_NAMES
        return haveIt


    def getDefaultLocaleName(self):
        """returns the default locale name"""
        return self.__defaultLocale

    
    def setDefaultLocaleName(self, localeName):
        """sets the default locale to be used by the class
        
        @param localeName (string) locale name
        @raise ValueError if locale name is not supported
        """
        if not self.hasLocaleName(localeName):
            raise ValueError('no such locale: "%s"' % localeName)
        self.__defaultLocale = localeName


    def listNames(self):
        """
        lists all available locale names and display names

        @return list[(QString(display-name1), locale-name1), (...)]
        
        Note: the list returned is sorted by localeName
        """

        if not self.__languageStrings:
            self.__languageStrings = CT_Language()

        out = []
        for localeName in LOCALE_NAMES:
            tr = getattr(self.__languageStrings, "LANG_" + localeName.upper())()
            out.append((tr, localeName))
        return out



    def getLanguageFile(self, localeName):
        """returns the full path to the language file for the specified locale


        If a language file for the specified locale name is not available a path
        to a default language file is returned. See getDefaultLocale().
        If the default language file could not be found empty string is returned.
        """
        if not self.hasLocaleName(localeName):
            localeName = self.getDefaultLocaleName()
        directory = os.path.dirname(__file__)
        fpath = os.path.join(directory, SZ_APP + '_' + localeName + '.qm')
        # no need to check for the files existance. Qt will handle it correctly.
        return fpath


    def getTranslator(self, parent, localeName):
        """
        returns an initialized QTranslator for the specified locale name

        @param parent parent of the QTranslator or None
        @param localeName name of the locale
        
        If a translator for the specified locale name is not available a default
        translator is returned. See getDefaultLocale().

        """
        translator = QtCore.QTranslator(parent)
        fpath = self.getLanguageFile(localeName)
        if fpath:
            translator.load(fpath)
        return translator


    def installTranslator(self, parent, localeName):
        """
        Installs a translator according to the specifed locale name

        @param parent parent of the translator
        @param localeName name of the locale for the translator
        @return QTranslator instance
        
        
        The new translator will replace the translator installed in the last
        call to this method. Use this method to dynamically switch translators.
        """
        translator = self.getTranslator(parent, localeName)
        if self.__translator:
            QtGui.QApplication.removeTranslator(self.__translator)
        self.__translator = translator
        QtGui.QApplication.installTranslator(translator)
        return self.__translator

