# -*- 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.

# TAL DummyDriver tailored to Glasnost needs

__doc__ = """Glasnost TAL Engine"""

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


import re
import sys
import traceback
import time

import glasnost.common.context as context

import GlasnostTALDriver

from TAL.TALDefs import NAME_RE, TALError, TALESError

try:
    from TAL.TALDefs import ErrorInfo
except ImportError:
    pass # backward compatible with tal 1.4


Default = []

name_match = re.compile(r"(?s)(%s):(.*)\Z" % NAME_RE).match

class CompilerError(Exception):
    pass


class GlasnostTALEngine:
    position = None
    source_file = None

    def __init__(self, macros=None):
        if macros is None:
            macros = {}
        self.macros = macros
        dict = {'nothing': None, 'default': Default}
        self.locals = self.globals = dict
        self.stack = [dict]

    def setSourceFile(self, source_file):
        self.source_file = source_file

    def createErrorInfo(self, err, position):
        return ErrorInfo(err, position)

    def getCompilerError(self):
        return CompilerError

    def setPosition(self, position):
        self.position = position

    def compile(self, expr):
        return "$%s$" % expr

    def uncompile(self, expression):
        assert expression[:1] == "$" == expression[-1:], expression
        return expression[1:-1]

    def beginScope(self):
        self.stack.append(self.locals)

    def endScope(self):
        assert len(self.stack) > 1, "more endScope() than beginScope() calls"
        self.locals = self.stack.pop()

    def setLocal(self, name, value):
        if self.locals is self.stack[-1]:
            # Unmerge this scope's locals from previous scope of first set
            self.locals = self.locals.copy()
        self.locals[name] = value

    def setGlobal(self, name, value):
        self.globals[name] = value
##    setLocal = setGlobal
   
    def evaluate(self, expression):
        assert expression[:1] == "$" == expression[-1:], expression
        expression = expression[1:-1]
        m = name_match(expression)
        if m:
            type, expr = m.group(1, 2)
        else:
            type = 'python'
            expr = expression
        if type == 'exists':
            return self.locals.has_key(expr) or self.globals.has_key(expr)
        if type == 'notexists':
            return not (self.locals.has_key(expr) or self.globals.has_key(expr))

        try:
            return eval(expr, self.globals, self.locals)
        except:
            if context.getVar('debug') and context.getVar('debugTal'):
                raise # gives more information
            raise TALESError("evaluation error in %s" % `expr`)


    def evaluateValue(self, expr):
        return self.evaluate(expr)

    def evaluateBoolean(self, expr):
        return self.evaluate(expr)

    def evaluateText(self, expr):
        text = self.evaluate(expr)
        if text is not None and text is not Default:
            text = str(text)
        return text

    def evaluateStructure(self, expr):
        # XXX Should return None or a DOM tree
        return self.evaluate(expr)

    def evaluateSequence(self, expr):
        # XXX Should return a sequence
        return self.evaluate(expr)

    def evaluateMacro(self, macroName):
        assert macroName[:1] == "$" == macroName[-1:], macroName
        macroName = macroName[1:-1]
        file, localName = self.findMacroFile(macroName)
        if not file:
            # Local macro
            macro = self.macros[localName]
        else:
            # External macro
            program, macros = GlasnostTALDriver.compilefile(file)
            macro = macros.get(localName)
            if not macro:
                raise TALESError("macro %s not found in file %s" %
                                 (localName, file))
        return macro

    def findMacroDocument(self, macroName):
        file, localName = self.findMacroFile(macroName)
        if not file:
            return file, localName
        doc = GlasnostTALDriver.parsefile(file)
        return doc, localName

    def findMacroFile(self, macroName):
        if not macroName:
            raise TALESError("empty macro name")
        i = macroName.rfind('/')
        if i < 0:
            # No slash -- must be a locally defined macro
            return None, macroName
        else:
            # Up to last slash is the filename
            fileName = macroName[:i]
            localName = macroName[i+1:]
            return fileName, localName


    def setRepeat(self, name, expr):
        seq = self.evaluateSequence(expr)
        return Iterator(name, seq, self)

    def getTALESError(self):
        return TALESError

    def getDefault(self):
        return Default



class Iterator:

    def __init__(self, name, seq, engine):
        self.name = name
        self.seq = seq
        self.engine = engine
        self.nextIndex = 0
        self.engine.setLocal('repeat_%s' % self.name, self)

    def next(self):
        i = self.nextIndex
        try:
            item = self.seq[i]
        except IndexError:
            return 0
        self.nextIndex = i+1
        self.engine.setLocal(self.name, item)
        return 1

    def __getattr__(self, attr):
        if attr == 'index':
            return self.nextIndex-1
        if attr == 'number':
            return self.nextIndex
        if attr == 'even':
            return not self.nextIndex%2
        if attr == 'odd':
            return self.nextIndex%2
        if attr == 'start':
            return self.nextIndex == 1
        if attr == 'end':
            return self.nextIndex == len(self.seq)
        if attr == 'length':
            return len(self.seq)
        if attr == 'letter':
            # doesn't work if nextIndex > 26
            return chr( ord('a')+self.nextIndex-1 )
        if attr == 'Letter':
            # doesn't work if nextIndex > 26
            return self.letter.upper()
        if attr == 'roman':
            rnvalues = (
                    (1000,'m'),(900,'cm'),(500,'d'),(400,'cd'),
                    (100,'c'),(90,'xc'),(50,'l'),(40,'xl'),
                    (10,'x'),(9,'ix'),(5,'v'),(4,'iv'),(1,'i'))
            n = self.index + 1
            s = ''
            for v, r in rnvalues:
                rct, n = divmod(n, v)
                s = s + r * rct
            return s
        if attr == 'Roman':
            return self.roman.upper()

    def first(self, expr):
        # for those two, see notes about first and last in Zope...
        if self.start:
            return 1
        i = self.nextIndex-1
        itemPrev = self.seq[i-1]
        itemNext = self.seq[i]
        if '.' in expr:
            valPrev = eval(expr, {'item':itemPrev})
            valNext = eval(expr, {'item':itemNext})
        else:
            valPrev = getattr(itemPrev, expr)
            valNext = getattr(itemNext, expr)
        return valPrev != valNext

    def last(item, expr):
        if item.end:
            return 1
        i = item.nextIndex
        itemPrev = item.seq[i-1]
        itemNext = item.seq[i]
        if '.' in expr:
            valPrev = eval(expr, {'item':itemPrev})
            valNext = eval(expr, {'item':itemNext})
        else:
            valPrev = getattr(itemPrev, expr)
            valNext = getattr(itemNext, expr)
        return valPrev != valNext

