########################################################################
#
# File Name:            4xslt.py
#
# Documentation:        http://docs.4suite.org/4XSLT/4xslt.py.html
#
"""
Command-line invokation of the 4RDF processor
WWW: http://4suite.org/4XSLT        e-mail: support@4suite.org

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

import os, sys, getopt
from Ft import __version__
from Ft.Lib import pDomlette
from Ft.Rdf import Model
from Ft.Rdf.Serializers.Dom import Serializer
import xml.dom.ext

def Run(options, args):
    dump = options.get('dump')
    serialize = options.get('serialize')
    driver = options.get('driver')
    dbname = options.get('dbname')
    sources = args.get('source-uri', [])

    if (dump or serialize) and sources:
        driver = "Memory"
    elif not driver:
        raise SystemExit("No driver specified")

    try:
        driver = "Ft.Rdf.Drivers." + driver
        driver_mod = __import__(driver, {}, {}, ["*"])
    except:
        raise SystemExit("Unknown driver '%s'" % driver)
        
    if driver_mod.ExistsDb(dbname):
        db = driver_mod.GetDb(dbname)
    else:
        db = driver_mod.CreateDb(dbname)

    db.begin()
    m = Model.Model(db)

    reader = pDomlette.PyExpatReader()
    serializer = Serializer()
    for source in sources:
        if source == '-':
            doc = reader.fromStream(sys.stdin)
        else:
            doc = reader.fromUri(source)
        serializer.deserialize(m, doc, '')
        reader.releaseNode(doc)

    if dump:
        stmts = m.complete(None, None, None)
        print 'The following is a list of remaining tuples, each in the form "subject, predicate, object".'
        print "["
        for stmt in stmts:
            print '("%s", "%s", "%s"),'%(stmt.subject, stmt.predicate, stmt.object)
        print "]"
            
    if serialize:
        outdoc = serializer.serialize(m)
        xml.dom.ext.PrettyPrint(outdoc)
        reader.releaseNode(outdoc)
            
    db.commit()
    return


from Ft.Lib.CommandLine import Options, CommandLineApp, Arguments, Command

class RdfCommandLineApp(CommandLineApp.CommandLineApp):

    def __init__(self):
        CommandLineApp.CommandLineApp.__init__(
            self,
            '4rdf',
            '4RDF version %s' % __version__,
            __doc__,
            [],
            ourOptions = Options.Options([Options.Option('d',
                                                         'dump',
                                                         'Dump the resulting triples from the specified file or database in Python'\
                                                         'list-of-tuple form to standard output (no presistent '\
                                                         'changes are made)',
                                                         ),
                                          #http://lists.w3.org/Archives/Public/w3c-rdfcore-wg/2001May/0264
                                          Options.Option('n',
                                                         'dump-n',
                                                         'Dump the resulting triples from the specified file or database"'\
                                                         'in "n-triples" form to standard output (no presistent '\
                                                         'changes are made)',
                                                         ),
                                          Options.Option('p',
                                                         'dump-p',
                                                         'Dump the resulting triples from the specified file or database'\
                                                         'in the W3C\'s prolog form to standard output (no presistent '\
                                                         'changes are made)',
                                                         ),
                                          Options.Option('s',
                                                         'serialize',
                                                         'Serialize the RDF from the given file or database '\
                                                         'to standard output (no presistent '\
                                                         'changes are made)',
                                                         ),
                                          Options.Option(None,
                                                         'driver=',
                                                         'Use the given 4RDF backend driver.',
                                                         ),
                                          Options.Option(None,
                                                         'dbName=',
                                                         'Update the RDF model database '\
                                                         'with the given name', 
                                                         ),
                                          ]),
            
            enableShowCommands = 0
            )

        self.function = Run
        self.arguments = [
            Arguments.ZeroOrMoreArgument('source-uri',
                                        'The URI of the source RDF document.  Note: if you use "-" as the name '\
                                        'of the source document, the source will  instead be read from standard input.',
                                        str),
            ]


    def validate_arguments(self,args):
        return Command.Command.validate_arguments(self,args)


