# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


__doc__ = """Glasnost TAL Generator"""

__version__ = '$Revision$'[11:-2]


from TAL.TALDefs import *
from TAL import TALGenerator

from glasnost.common.tools import *
import glasnost.common.context as context
from glasnost.proxy.tools import getProxyForServerRole

from glasnost.web.GlasnostTALEngine import GlasnostTALEngine
import glasnost.common.xhtmlgenerator as X


TALGenerator.KNOWN_TAL_ATTRIBUTES.append('translate')
TALGenerator.KNOWN_TAL_ATTRIBUTES.append('attr-translate')
TALGenerator.KNOWN_TAL_ATTRIBUTES.append('reroot')


class GlasnostTALGenerator(TALGenerator.TALGenerator):
    
    def __init__(self, expressionCompiler=None, xml=1):
        self.macros = {}
        self.inTagToTranslate = 0
        self.attrsToTranslate = []
        if not expressionCompiler:
            expressionCompiler = GlasnostTALEngine(self.macros)
        TALGenerator.TALGenerator.__init__(self, expressionCompiler, xml)

    actionIndex = { 'replace': 0, 'insert': 1, 'metal': 2, 'tal': 3, 'xmlns': 4,
                    'translate':5, 'attr-translate':6, 'reroot':7,
                     0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6:6, 7:7}

    def getTranslation(self, text, sourceLanguage = 'en'):
        virtualHost = context.getVar('virtualHost')
        if sourceLanguage == context.getVar('readLanguages')[0]:
            return text
        if sourceLanguage == 'en' and (
                    hasattr(_.im_self, '_catalog') and 
                    _.im_self._catalog.has_key(text.strip())):
            return _(text.strip())
        translationsProxy = getProxyForServerRole('translations')
        if translationsProxy and virtualHost and virtualHost.id:
            text, language, state = translationsProxy.getTranslationInfos(
                        text.strip(), # sourceString
                        virtualHost.id, # sourceId
                        repr(text.strip()), # sourcePath
                        sourceLanguage, # sourceLanguage
                        context.getVar('readLanguages') # destinationLanguage
                        )
        elif not virtualHost: # when precompiling templates
            raise faults.StringNotAvailableThroughGettext(text)

        return text

    # I'd like those strings to be translated through gettext but they are from
    # TAL templates and I don't want to write a tool to grab them.
    N_('Search')
    N_('You are not logged in')
    N_('Go')
    N_('All Objects')

    def emitRawText(self, text):
        if self.inTagToTranslate:
            text = self.getTranslation(text.strip(), self.inTagToTranslate)
            self.inTagToTranslate = None
        self.emit("rawtext", text)

    def emitStartElement(self, name, attrlist, taldict, metaldict,
                         position=(None, None), isend=0):

        if taldict:
            if taldict.has_key('translate'):
                language = taldict['translate'] or 'en'
                # we put sth in the tag so TALGenerator won't throw a missing
                # value exception
                taldict['translate'] = 'foo'
                self.inTagToTranslate = language
            if taldict.has_key('attr-translate'):
                attrsToTranslate = taldict['attr-translate'].split()
                del taldict['attr-translate']
                newAttrList = []
                for attr in attrlist:
                    if not attr[0] in attrsToTranslate:
                        newAttrList.append(attr)
                    else:
                        newAttrList.append( (attr[0], self.getTranslation(attr[1])) )
                attrlist = newAttrList
            if taldict.has_key('reroot'):
                attrsToReRoot = taldict['reroot'].split()
                newAttrList = []
                for attr in attrlist:
                    option = ''
                    if not attr[0] in [x.split(':')[0] for x in attrsToReRoot]:
                        newAttrList.append(attr)
                    else:
                        options = [x.split(':')[1] for x in attrsToReRoot \
                                    if ':' in x and x.startswith('%s:' % attr[0]) ]
                        url = X.url(attr[1]).getAsUrl()
                        if options:
                            option = options[0]
                            if option == 'absolute':
                                url = X.url(attr[1]).getAsAbsoluteUrl()
                        newAttrList.append( (attr[0], url) )
                attrlist = newAttrList

        TALGenerator.TALGenerator.emitStartElement(self, name, attrlist,
                taldict, metaldict, position, isend)

