# -*- 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 Translations Proxy"""

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


import md5

import glasnost.common.context as context
import glasnost.common.faults as faults
import glasnost.common.tools_new as commonTools
from glasnost.common.TranslationsCommon import *

from DispatcherProxy import callServer, getApplicationToken
from ObjectsProxy import register, AdminWithoutWritersMixin, \
        AdministrableProxyMixin, ObjectProxyMixin, Proxy
from tools import *

import kinds
import widgets

class AdminTranslations(AdminWithoutWritersMixin, AdminTranslationsCommon):
    pass
register(AdminTranslations)


class Localization(ObjectProxyMixin, LocalizationCommon):
    pass
register(Localization)


class TranslationsProxy(TranslationsCommonMixin, AdministrableProxyMixin,
                        Proxy):
    def canDeleteLocalization(self, localizationKey, sourceStringDigest,
                              serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        return callServer(
            serverId,
            'canDeleteLocalization',
            [serverId, getApplicationToken(), userToken, localizationKey,
             sourceStringDigest])

    def canModifyLocalization(self, localizationKey, sourceStringDigest,
                              serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        return callServer(
            serverId,
            'canModifyLocalization',
            [serverId, getApplicationToken(), userToken, localizationKey,
             sourceStringDigest])
    
    def getLanguagesForObjectId(self, objectId):
        userToken = context.getVar('userToken', default = '')
        serverId = commonTools.makeApplicationId(objectId, self.serverRole)
        return callServer(
            serverId,
            'getLanguagesForObjectId',
            [serverId, getApplicationToken(), userToken, objectId])

    def getSomeDigestsAndLabels(self, localizationKey, digestsAndLabelsCount,
                                possibleStates, serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        if possibleStates is None:
            possibleStates = []
        digestsAndLabels = callServer(
            serverId,
            'getSomeDigestsAndLabels',
            [serverId, getApplicationToken(), userToken,
             localizationKey, digestsAndLabelsCount, possibleStates])
        for digestAndLabel in digestsAndLabels:
            digestAndLabel[1] = iso8859_15(digestAndLabel[1])
        return digestsAndLabels

    def getLocalization(self, localizationKey, sourceStringDigest,
                        serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        localizationImport = callServer(
            serverId,
            'getLocalization',
            [serverId, getApplicationToken(), userToken,
             localizationKey, sourceStringDigest])
        return commonTools.importThing(localizationImport)

    def getPossibleLanguages(self, serverId = None):
        serverId = self.getServerId(serverId = serverId)
        cache = context.getVar('temporaryCache')
        if cache is not None:
            try:
                return cache['possible-languages-%s' % serverId]
            except KeyError:
                pass
        userToken = context.getVar('userToken', default = '')
        result = callServer(
                serverId,
                'getPossibleLanguages',
                [serverId, getApplicationToken(), userToken])
        if cache is not None:
            cache['possible-languages-%s' % serverId] = result
        return result

    def getTranslation(self, sourceString, sourceId, sourcePath,
                       sourceLanguage, destinationLanguages, multiCall = None):
        if not sourceString:
            if multiCall:
                multiCall.addEarlyResult('')
                return None
            else:
                return ''
        if not sourceId or not sourceLanguage:
            if multiCall:
                multiCall.addEarlyResult(sourceString)
                return None
            else:
                return sourceString
        sourceStringDigest = md5.new(sourceString.replace(
            '\r\n', '\n')).hexdigest()
        cacheKey = '_' .join([sourceStringDigest,
                              sourceLanguage,
                              str(destinationLanguages)])
        cache = context.getVar('cache')
        if cache is not None and cache.has_key(cacheKey):
            result = cache[cacheKey]
            if multiCall:
                multiCall.addEarlyResult(result)
                return None
            else:
                return result

        def handleResult(lazyTranslation, sourceString = sourceString,
                         cacheKey = cacheKey):
            try:
                result = iso8859_15(lazyTranslation())
                cache = context.getVar('cache')
                if cache is not None:
                    cache[cacheKey] = result
                return result
            except faults.UnknownStringDigest:
                if context.getVar('debug'):
                    raise faults.UnknownStringDigest(sourceString)
                return sourceString
            except faults.UnknownServerId:
                return sourceString
            except:
                if context.getVar('debug'):
                    raise
                return sourceString

        userToken = context.getVar('userToken', default = '')
        serverId = commonTools.makeApplicationId(sourceId, self.serverRole)
        try:
            return callServer(
                    serverId,
                    'getTranslation',
                    [serverId, getApplicationToken(), userToken,
                     sourceStringDigest, sourceId, sourcePath, sourceLanguage,
                     destinationLanguages],
                    resultHandler = handleResult,
                    multiCall = multiCall)
        except faults.UnknownStringDigest:
            if multiCall:
                raise
            if context.getVar('debug'):
                raise faults.UnknownStringDigest(sourceString)
            return sourceString
        except faults.UnknownServerId:
            if multiCall:
                raise
            return sourceString

    def getTranslationInfos(self, sourceString, sourceId, sourcePath,
                            sourceLanguage, destinationLanguages,
                            ignoreNew = 0, multiCall = None):
        assert sourceId
        assert sourceLanguage
        sourceStringDigest = md5.new(sourceString.replace(
                '\r\n', '\n')).hexdigest()
        def handleResult(lazyInfos, sourceString = sourceString):
            try:
                infos = lazyInfos()
            except faults.UnknownStringDigest:
                # FIXME: we don't know the source language here
                return (sourceString, '', 'untranslated')
            infos[0] = iso8859_15(infos[0])
            return infos
        userToken = context.getVar('userToken', default = '')
        serverId = commonTools.makeApplicationId(sourceId, self.serverRole)
        try:
            return callServer(
                serverId,
                'getTranslationInfos',
                [serverId, getApplicationToken(), userToken,
                 sourceStringDigest, sourceId, sourcePath, sourceLanguage,
                 destinationLanguages, ignoreNew],
                resultHandler = handleResult,
                multiCall = multiCall)
        except (faults.UnknownServerId, faults.UnknownDispatcherInId):
            if multiCall:
                raise
            return (sourceString, sourceLanguage, 'untranslated')

    def getTranslatorLocalizationKeys(self, serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        return callServer(
            serverId,
            'getTranslatorLocalizationKeys',
            [serverId, getApplicationToken(), userToken])

    def hasLocalization(self, localizationKey, sourceStringDigest,
                        serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        return callServer(
            serverId,
            'hasLocalization',
            [serverId, getApplicationToken(), userToken, localizationKey,
             sourceStringDigest])

    def hasSourceString(self, localizationKey, sourceStringDigest,
                        serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        return callServer(
            serverId,
            'hasSourceString',
            [serverId, getApplicationToken(), userToken, localizationKey,
             sourceStringDigest])

    def modifyLocalization(self, localization, serverId = None):
        userToken = context.getVar('userToken', default = '')
        serverId = self.getServerId(serverId = serverId)
        localizationExport = localization.exportToXmlRpc()
        localization.version = callServer(
            serverId,
            'modifyLocalization',
            [serverId, getApplicationToken(), userToken,
             localizationExport])
        return None
