from Ft.Rdf import RDF_MS_BASE, RDF_SCHEMA_BASE

import Context
from Context import ContextFromKeyWord
from Ft import FtException

class CompiletimeException(FtException):
    INTERNAL = 1
    SYNTAX = 2
    PROCESSING = 3

    def __init__(self, errorCode, *args):
        import MessageSource
        FtException.__init__(self, errorCode, MessageSource.COMPILETIME, args)
        return


class RuntimeException(FtException):
    INTERNAL = 1
    NO_CONTEXT = 10
    UNDEFINED_VARIABLE = 100
    UNDEFINED_PREFIX = 101
    WRONG_ARGUMENTS = 200

    def __init__(self, errorCode, *args):
        import MessageSource
        FtException.__init__(self, errorCode, MessageSource.RUNTIME, args)
        return


def CreateContext(**kw):
    return ContextFromKeyWord(kw)

CreateContext.__doc__ = ContextFromKeyWord.__doc__

def Evaluate(expression, **kw):
    """
    Creates a context for the expression.  See Context.ContextFromKeyWord for a complete description
    Then Compiles and evaluates the expression
    """
    con = Context.ContextFromKeyWord(kw)
    exp = Compile(expression)
    return exp.evaluate(con)


def Compile(expression):
    """
    Compile a Versa expression into a compilied object.
    You can then call evaluate on the object passing in
    a Context. See CreateContext
    """
    p = parser.new()
    import os
    if os.environ.has_key('DEBUG_VERSA'):
        try:
            p.debug_mode(1)
        except:
            p.debug = 1
    try:
        return p.parse(expression)
    except SyntaxError, error:
        raise CompiletimeException(CompiletimeException.SYNTAX, 0, 0,
                                   str(error))
    except:
        import traceback, cStringIO
        stream = cStringIO.StringIO()
        traceback.print_exc(None, stream)
        raise RuntimeException(RuntimeException.INTERNAL, stream.getvalue())


VERSA_NS = "http://rdfinference.org/versa/0/2/"


import DataTypes

RDF_TYPE_PROP = DataTypes.Resource(RDF_MS_BASE + 'type')
RDF_SUBCLASSOF_PROP = DataTypes.Resource(RDF_SCHEMA_BASE + 'subClassOf')
RDF_SUBPROPOF_PROP = DataTypes.Resource(RDF_SCHEMA_BASE + 'subPropertyOf')


class Constants:
    SORT_NUMBER = DataTypes.Resource(VERSA_NS + 'sort/number')
    SORT_STRING = DataTypes.Resource(VERSA_NS + 'sort/string')
    SORT_ASCENDING = DataTypes.Resource(VERSA_NS + 'sort/ascending')
    SORT_DESCENDING = DataTypes.Resource(VERSA_NS + 'sort/descending')

    TRAVERSE_SIMPLE = DataTypes.Resource(VERSA_NS + 'traverse/simple')
    TRAVERSE_TRANS = DataTypes.Resource(VERSA_NS + 'traverse/transitive')
    TRAVERSE_FWD = DataTypes.Resource(VERSA_NS + 'traverse/forward')
    TRAVERSE_INV = DataTypes.Resource(VERSA_NS + 'traverse/inverse')
    TRAVERSE_ANY = DataTypes.Resource(VERSA_NS + 'traverse/any')
    #TRAVERSE_TRANS_LEAVES = DataTypes.Resource(VERSA_NS + 'traverse/trans-leaves')
    #TRAVERSE_ALL = DataTypes.Resource(VERSA_NS + 'traverse/all')

g_extFunctions = {}

import VersaParserc as VersaParser
parser = VersaParser
