########################################################################
#
# File Name:            Context.py
#
#
"""

Context that is passed around for the current evaluation

WWW: http://4suite.org/4XSLT        e-mail: support@4suite.org

Copyright (c) 1999-2001 Fourthought Inc, USA.   All Rights Reserved.
See  http://4suite.org/COPYRIGHT  for license and copyright information
"""

from Ft.Rdf import RDF_MS_BASE, RDF_SCHEMA_BASE
from Ft.Rdf import RdfException
import ResourceExpressions


class Context:
    def __init__(self, driver, nsMapping, varBindings, scope=None):
        self.driver = driver
        self.nsMapping = nsMapping
        self.varBindings = varBindings
        self.current = None
        self.cachedSuperProps = None
        self.scope = scope
        return

    def isTransitive(self, property):
        if property in TRANSITIVE_BY_RULE:
            return 1
        return 0

    def clone(self):
        new_con = Context(self.driver, self.nsMapping.copy(),
                          self.varBindings.copy(), self.scope)
        new_con.current = self.current
        if self.cachedSuperProps is not None:
            new_con.cachedSuperProps = self.cachedSuperProps.copy()
        return new_con

    def getCachedSuperProps(self):
        from Ft.Rdf.Parsers.Versa import RDF_TYPE_PROP, RDF_SUBCLASSOF_PROP, RDF_SUBPROPOF_PROP
        if self.cachedSuperProps is None:
            self.cachedSuperProps = ResourceExpressions.GetRelations(
                None, RDF_SUBPROPOF_PROP, self, 1, 0
                )
        return self.cachedSuperProps


def ContextFromKeyWord(kw):
    """Create a new context for processing, allowed params:
       model = an instance of an Ft.Rdf.Model.Model
       driver = an instance of Ft.Rdf.Drivers.*
       nsMapping = a dictionary that map prefix to namespace
       varBindings = a dictionary.  keys are a tuple of (namepsace,localName) and values are any allowed data type
       """

    defaultNs = {'rdf':RDF_MS_BASE,
                 'rdfs':RDF_SCHEMA_BASE,
                 }
    driver=None
    nsMapping = defaultNs
    varBindings = {}
    scope = None

    for name, value in kw.items():
        if name == 'driver':
            driver = value
        elif name == 'model':
            driver = value._driver
        elif name == 'nsMapping':
            nsMapping = value.copy()
            nsMapping.update(defaultNs)
        elif name == 'varBindings':
            varBindings = value
        elif name == 'scope':
            scope = value
        else:
            raise RdfException(FtRdfException.INVALID_ARGUMENT, name=name)
    if driver is None:
        raise RdfException(FtRdfException.MISSING_DRIVER)
    return Context(driver, nsMapping, varBindings, scope)


import DataTypes
TRANSITIVE_BY_RULE = [DataTypes.Resource(RDF_SCHEMA_BASE + 'subPropertyOf'),
                      DataTypes.Resource(RDF_SCHEMA_BASE + 'subClassOf')]

