/* xsltparser.c  --  Generic XSLT parser for eurephiadm
 *
 *  GPLv2 only - Copyright (C) 2009 - 2012
 *               David Sommerseth <dazo@users.sourceforge.net>
 *
 *  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; version 2
 *  of the License.
 *
 *  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

/**
 * @file   xsltparser.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @date   2009-03-29
 *
 * @brief  Generic XSLT parser for eurephiadm
 *
 */

#include <stdio.h>

#ifdef HAVE_LIBXML2
#include <libxml/tree.h>
#include <libxml/xmlstring.h>
#endif

#ifdef HAVE_LIBXSLT
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#endif

#include <eurephia_values.h>


/**
 * Parses an XML document and a given XSLT file and returns the result as text to a FILE pointer.
 *
 * @param dst        FILE pointer where the result will be returned
 * @param cfg        eurephiaVALUES with the eurephiadm configuration.  Used for locating the correct
 *                   path to the XSLT templates
 * @param xmldoc     xmlDoc pointer to the input XML document.
 * @param xsltfname  File name of the XSLT template to use for the parsing.
 * @param xsltparams Parameters to the XSLT template.
 *
 * @return Returns 1 on success, otherwise 0.
 */
int xslt_print_xmldoc(FILE *dst, eurephiaVALUES *cfg, xmlDoc *xmldoc,
                      const char *xsltfname, const char **xsltparams)
{
#ifdef HAVE_LIBXSLT
        xmlDoc *result = NULL;
        xsltStylesheet *xslt = NULL;
        xmlChar xsltfile[2048];

        // Build up complete path to the XSLT template we will use
        xmlStrPrintf(xsltfile,2046, "%s/%s%c", eGet_value(cfg, "eurephiadm_xslt_path"), xsltfname, 0);

        // Load the XSLT template
        xsltInit();
        xslt = xsltParseStylesheetFile(xsltfile);
        if( xslt == NULL ) {
                return 0;
        }

        // Parse the XML document, using the XSLT template
	result = xsltApplyStylesheet(xslt, xmldoc, xsltparams);
        if( result == NULL ) {
                return 0;
        }

        // Send the result to file
        xsltSaveResultToFile(dst, result, xslt);

        // Clean up
        xmlFreeDoc(result);
	xsltFreeStylesheet(xslt);
        xsltCleanupGlobals();
        return 1;
#else
        return 0;
#endif
}
