//  Copyright (2013) Cédric Coussinet (cedric.coussinet@nomoseed.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, either version 3 of the License, or
//  (at your option) any later version.
//
//  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, see <http://www.gnu.org/licenses/>

#include <QDir>

#include <libxml/parser.h>
#include <libxslt/xslt.h>
#include <libxslt/transform.h>

#include <libxslt/xsltutils.h>

#include <QFile>

#include "automaton.h"

void formalismActualize(const char* file)
{
    QFile error("formalism.log");
    error.open(QFile::WriteOnly);
    xmlSubstituteEntitiesDefault (1);
    xmlLoadExtDtdDefaultValue = 1;
    xsltStylesheetPtr xsl;
    xsl = xsltParseStylesheetFile ((const xmlChar *) "formalisms/automaton/automaton.xsl");
    if (xsl){
        xmlDocPtr doc;
        doc = xmlReadFile (file, "UTF-8", 0 );
        if (doc){
            const QByteArray dir(QString("\""+QDir::currentPath()+"\"").toUtf8());
            const char * params[3];
            params[0]= "base";
            params[1]= dir.constData();
            params[2]= NULL;
            xmlDocPtr out = xsltApplyStylesheet(xsl, doc, params);
            if (out){
                xmlSaveFileEnc(file, out, "UTF-8");
                xmlFreeDoc (out);
            }
            else
                error.write("automaton : xslt error.");
            xmlFreeDoc (doc);
        }
        else
            error.write("automaton : loading "+ QString(file).toUtf8() +" failed.");
        xsltFreeStylesheet (xsl);
    }
    else
        error.write("automaton : loading formalisms/automaton/automaton.xsl failed.");
    error.close();
    xsltCleanupGlobals ();
    xmlCleanupParser ();
}
