########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Server/Client/Commands/Render.py,v 1.12 2004/09/23 20:53:27 mbrown Exp $
"""
Implementation of '4ss render' command
(functions defined here are used by the Ft.Lib.CommandLine framework)

Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

__doc__ = """This command will use 4xslt to render a source document \
with an XSLT stylesheet. Both the source and stylesheet must exist in \
a 4Suite repository, although the source document can be a virtual \
document such as the metadata XML for any resource in the repository.
If necessary, you will be prompted first for credentials and access \
info to connect to the repository."""


import sys

from Ft.Server.Client import FtServerClientException
from Ft.Server.Client.Commands import CommandUtil
from Ft.Xml.Xslt._4xslt import g_paramBindingPattern


def Run(options, args):
    defs = options.get('define', [])
    if not isinstance(defs, list):
        defs = [defs]

    top_level_params = {}
    for d in defs:
        match = g_paramBindingPattern.match(d)
        top_level_params[match.group(1)] = match.group(2)

    repo = CommandUtil.GetRepository(options, '4ss.render')
    if repo is not None:
        commit = False
        try:
            doc = repo.fetchResource(args['path'])
            stys = []
            for path in args['stylesheet']:
                stys.append(doc.fetchResource(path))
            res, imt = doc.applyXslt(stys, params=top_level_params)
            # commit because the transformation may have had side effects
            commit = True
            sys.stderr.write("Internet Media Type of result: %s\n" % imt)
            sys.stderr.flush()
            sys.stdout.write(res)
            sys.stdout.flush()
            if res[-1] != '\n':
                sys.stderr.write('\n')
                sys.stderr.flush()
        finally:
            try:
                if commit:
                    repo.txCommit()
                else:
                    repo.txRollback()
            except:
                pass

    return


def Register():
    from Ft.Lib.CommandLine import Options, Command, Arguments
    cmd = Command.Command('render',
                          'Perform an XSLT transformation using documents in a repository',
                          '/fourthought.com',
                          __doc__,
                          function = Run,
                          arguments=[Arguments.RequiredArgument('path',
                                                                "the path of the source document",
                                                                str),
                                     Arguments.OneOrMoreArgument('stylesheet',
                                                                 "the path of the stylesheet",
                                                                 str),
                                     ],
                          options=Options.Options([
                                     Options.Option('D',
                                                    'define=NAME=VALUE',
                                                    'Bind a top-level parameter'
                                                    ),
                          ]),
                          fileName = __file__,
                          )
    return cmd
