/**
 * Copyright 2009  Michael Leupold <lemma@confuego.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3, or any
 * later version accepted by the membership of KDE e.V. (or its
 * successor approved by the membership of KDE e.V.), which shall
 * act as a proxy defined in Section 6 of version 3 of the license.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "xsltransformation.h"
#include "xmlkioentitiesloader.h"
#include "parserprivate.h"

#include <QtCore/QTextCodec>

#include <KDebug>

extern "C" {
    #include <libxml/parserInternals.h>
    #include <libxml/xmlmemory.h>
    #include <libxml/debugXML.h>
    #include <libxml/xinclude.h>
    #include <libxml/catalog.h>
    #include <libxml/xinclude.h>
    #include <libxslt/xslt.h>
    #include <libxslt/transform.h>
    #include <libxslt/xsltutils.h>
    #include <libxslt/variables.h>
}

XslTransformation::XslTransformation()
    : m_xsltStylesheet(0), m_inputDoc(0), m_mimeType("text/xml")
{
}

XslTransformation::~XslTransformation()
{
    xsltFreeStylesheet(m_xsltStylesheet);
    xmlFreeDoc(m_inputDoc);
}

bool XslTransformation::loadStylesheet(const KUrl &url)
{
    if (m_inputUrl.isEmpty()) {
        kDebug() << "Call setInput before calling loadStylesheet";
        return false;
    }
    
    if (url.isEmpty() || !url.isValid() || url.isRelative()) {
        TransformationError error;
        error.m_errorType = TransformationError::ErrorInvalid;
        error.m_file = url;
        m_errors.append(error);
        return false;
    }

    if (m_inputUrl.hasHost() && !url.hasHost()) {
        TransformationError error;
        error.m_errorType = TransformationError::ErrorSecurity;
        error.m_file = url;
        m_errors.append(error);
        return false;
    }

    xmlParserCtxtPtr pctxt;
    pctxt = ParserPrivate::createParserContext(!url.hasHost(), 0,
                                               XML_PARSE_RECOVER | XML_PARSE_NOENT |
                                               XML_PARSE_DTDLOAD);
    if (pctxt == 0) {
        return false;
    }
    QByteArray urlData(url.toEncoded());
    xmlParserInputPtr parserInput = xmlNewInputFromFile(pctxt, urlData.constData());
    if (parserInput == 0) {
        // TODO: get the context's error messages
        ParserPrivate::contextGetErrors(pctxt);
        ParserPrivate::freeParserContext(pctxt);
        return false;
    }
    inputPush(pctxt, parserInput);
    if (pctxt->directory == 0) {
        pctxt->directory = xmlParserGetDirectory(urlData.constData());
    }
    xmlParseDocument(pctxt);
    xmlDocPtr styleDoc = ParserPrivate::freeParserContext(pctxt);
    if (styleDoc == 0) {
        return false;
    }

    // TODO: XInclude processing is not implemented for a reason.
    //       xmlXIncludeProcess doesn't allow us to install a loader of
    //       its own and doesn't use a custom entity loader. Thus there's
    //       now way XInclude processing can currently be bade safe.

    bool rc = false;
    ParserPrivate::docCreatePrivate(styleDoc);
    m_xsltStylesheet = xsltParseStylesheetDoc(styleDoc);
    m_errors.append(ParserPrivate::docGetErrors(styleDoc));
    ParserPrivate::docFreePrivate(styleDoc);
    if (m_xsltStylesheet) {
        rc = true;
    } else {
        xmlFreeDoc(styleDoc);
    }

    return rc;
}

bool XslTransformation::setInput(const KUrl &url, const QString &input)
{
    m_inputUrl = url;
    QByteArray inputData(input.toUtf8());
    QByteArray urlData(url.toEncoded());

    // no XINCLUDE due to possible unhandled security problems (remote file
    // including locale file)
    xmlParserCtxtPtr pctxt;
    pctxt = ParserPrivate::createParserContext(!url.hasHost(), 0,
                                               XML_PARSE_RECOVER | XML_PARSE_NOENT |
                                               XML_PARSE_DTDLOAD);
    if (pctxt == 0) {
        return false;
    }
    
    xmlParserInputBufferPtr buffer = xmlParserInputBufferCreateMem(inputData.constData(),
                                                                   inputData.size(),
                                                                   XML_CHAR_ENCODING_UTF8);
    xmlParserInputPtr parserInput = xmlNewIOInputStream(pctxt, buffer, XML_CHAR_ENCODING_UTF8);
    parserInput->filename = (char *)xmlStrdup((const xmlChar*)urlData.constData());
    inputPush(pctxt, parserInput);
    if (pctxt->directory == 0) {
        pctxt->directory = xmlParserGetDirectory(urlData.constData());
    }
    xmlParseDocument(pctxt);
    // TODO: get the conext's error messages
    ParserPrivate::contextGetErrors(pctxt);
    
    m_inputDoc = ParserPrivate::freeParserContext(pctxt);

    // TODO: XInclude processing is not implemented for a reason.
    //       xmlXIncludeProcess doesn't allow us to install a loader of
    //       its own and doesn't use a custom entity loader. Thus there's
    //       now way XInclude processing can currently be bade safe.
    
    // TODO: everything freed?
    
    return (m_inputDoc ? true : false);
}

bool XslTransformation::transform()
{
    if (!m_xsltStylesheet || !m_inputDoc) {
        return false;
    }

    const char *params[1];
    params[0] = NULL;

    bool rc = false;

    // disable writing and reading from disk
    xsltTransformContextPtr transformCtxt;
    transformCtxt = ParserPrivate::createTransformContext(m_xsltStylesheet,
                                                          m_inputDoc);
    xmlDocPtr outputDoc = xsltApplyStylesheetUser(m_xsltStylesheet, m_inputDoc, params,
                                                  0, 0, transformCtxt);
    m_errors.append(ParserPrivate::contextGetErrors(transformCtxt));
    ParserPrivate::freeTransformContext(transformCtxt);
    if (outputDoc) {
        // figure out mimetype
        if (m_xsltStylesheet->method) {
            QString strMethod((const char*)m_xsltStylesheet->method);
            if (strMethod == QLatin1String("xml")) {
                m_mimeType = "application/xhtml+xml";
            } else if (strMethod == QLatin1String("html")) {
                m_mimeType = "text/html";
            }
        } else {
            bool isHtml = true;
            xmlNodePtr child = outputDoc->children;
            while (child) {
                if (child->type == XML_ELEMENT_NODE) {
                    // found first child element, if name is not html => xml
                    if (QString((const char*)child->name).toLower() != QLatin1String("html")) {
                        isHtml = false;
                    }
                    break;
                } else if (child->type == XML_TEXT_NODE) {
                    // found text node, if it doesn't contain only spaces => xml
                    QString content((const char*)child->content);
                    if (!content.trimmed().isEmpty()) {
                        isHtml = false;
                        break;
                    }
                }
                child = child->next;
            }
            m_mimeType = (isHtml ? "text/html" : "application/xhtml+xml");
        }

        xmlChar *outputData;
        int outputSize;
        if (xsltSaveResultToString(&outputData, &outputSize, outputDoc,
                                   m_xsltStylesheet) == 0) {
            if (m_xsltStylesheet->encoding) {
                QTextCodec *codec;
                codec = QTextCodec::codecForName((const char*)m_xsltStylesheet->encoding);
                if (codec) {
                    m_output = codec->toUnicode((const char*)outputData);
                    rc = true;
                } else {
                    TransformationError error;
                    error.m_errorType = TransformationError::ErrorEncoding;
                    error.m_message = QString("Unknown output encoding: %1")
                        .arg((const char*)m_xsltStylesheet->encoding);
                    m_errors.append(error);
                }  
            } else {
                m_output = QString::fromUtf8((const char*)outputData);
                rc = true;
            }
            xmlFree(outputData);
        }

        xmlFreeDoc(outputDoc);
    }

    if (!rc) {
        kDebug() << "XSL transformation failed";
    }

    return rc;
}

QString XslTransformation::output() const
{
    return m_output;
}

QString XslTransformation::mimeType() const
{
    return m_mimeType;
}

bool XslTransformation::hasError() const
{
    return !m_errors.isEmpty();
}

QList<TransformationError> XslTransformation::errors() const
{
    return m_errors;
}
