from types import StringType, UnicodeType
from AccessControl import ClassSecurityInfo
from Products.Localizer.Utils import charsets, get_language_name, lang_negotiator
security = ClassSecurityInfo()
security.declarePublic('gettext')
# set default for add = 0
_marker = []
def gettext(self, message, lang=None, add=0, default=_marker):
    """Returns the message translation from the database if available.

    If add=1, add any unknown message to the database.
    If a default is provided, use it instead of the message id
    as a translation for unknown messages.
    """

    if type(message) not in (StringType, UnicodeType):
        raise TypeError, 'only strings can be translated.'

    message = message.strip()

    if default is _marker:
        default = message

    # Add it if it's not in the dictionary
    if add and not self._messages.has_key(message) and message:
        self._messages[message] = PersistentMapping()

    # Get the string
    if self._messages.has_key(message):
        m = self._messages[message]

        if lang is None:
            # Builds the list of available languages
            # should the empty translations be filtered?
            available_languages = list(self._languages)

            # Get the language!
            lang = lang_negotiator(available_languages)

            # Is it None? use the default
            if lang is None:
                lang = self._default_language

        if lang is not None:
            return m.get(lang) or default

    return default
from Products.Localizer.MessageCatalog import MessageCatalog
MessageCatalog.gettext = gettext

