/* BdfServer - Copyright (c) 2013-2020 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.tools.exportation.transformation.compilers;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.configuration.PathConfiguration;
import fr.exemole.bdfserver.api.exportation.transformation.SimpleTemplateFactory;
import fr.exemole.bdfserver.api.storage.TemplateStorage;
import fr.exemole.bdfserver.tools.exportation.transformation.BdfTransformationUtils;
import fr.exemole.bdfserver.tools.exportation.transformation.XsltSimpleTemplateFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import net.fichotheque.exportation.transformation.TemplateKey;
import net.fichotheque.extraction.def.ExtractionDef;
import net.fichotheque.tools.exportation.transformation.TemplateContentDescriptionBuilder;
import net.mapeadores.util.io.BufferErrorListener;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.logging.LogUtils;
import net.mapeadores.util.logging.MessageHandler;


/**
 *
 * @author Vincent Calame
 */
public class XsltSimpleTemplateCompiler extends SimpleTemplateCompiler {

    private final static String ERROR_CATEGORY = "error";
    private final static String WARNING_CATEGORY = "warning";
    private final static String TRANSFORMER_PATH = "transformer.xsl";
    private final static String EXTRACTION_PATH = "extraction.xml";

    public XsltSimpleTemplateCompiler(BdfServer bdfServer, PathConfiguration pathConfiguration, TemplateKey templateKey, MessageHandler messageHandler) {
        super(bdfServer, pathConfiguration, templateKey, messageHandler);
    }

    @Override
    public SimpleTemplateFactory compile(TemplateStorage.Unit storageUnit) throws CompilationException {
        String baseURI = TemplateCompilerUtils.getBaseURI(storageUnit.getTemplateKey());
        ExtractionDef customExtractionDef = getExtractionDef(storageUnit, EXTRACTION_PATH, false);
        InputStream inputStream;
        try {
            inputStream = TemplateCompilerUtils.getContentInputStream(storageUnit, TRANSFORMER_PATH);
        } catch (IOException ioe) {
            addError("_ error.exception.transformation_io", TRANSFORMER_PATH, ioe.getMessage());
            throw new CompilationException();
        }
        if (inputStream == null) {
            addError("_ error.empty.transformation.ressource", TRANSFORMER_PATH);
            throw new CompilationException();
        }
        String xsltString;
        try (InputStream is = inputStream) {
            xsltString = IOUtils.toString(is, "UTF-8");
        } catch (IOException ioe) {
            addError("_ error.exception.transformation_io", TRANSFORMER_PATH, ioe.getMessage());
            throw new CompilationException();
        }
        TemplateContentDescriptionBuilder templateContentDescriptionBuilder = newTemplateContentDescriptionBuilder(TRANSFORMER_PATH, true);
        if (!TemplateCompilerUtils.testXml(xsltString, templateContentDescriptionBuilder)) {
            throw new CompilationException();
        }
        TransformerFactory factory = BdfTransformationUtils.newTransformationFactory(bdfServer, pathConfiguration);
        String systemId = baseURI + TRANSFORMER_PATH;
        Source source = new StreamSource(new StringReader(xsltString), systemId);
        BufferErrorListener errorListener = new BufferErrorListener();
        factory.setErrorListener(errorListener);
        try {
            Templates templates = factory.newTemplates(source);
            for (TransformerException te : errorListener.getErrorList()) {
                LogUtils.handleTransformerException(ERROR_CATEGORY, te, systemId, templateContentDescriptionBuilder);
            }
            for (TransformerException te : errorListener.getWarningList()) {
                LogUtils.handleTransformerException(WARNING_CATEGORY, te, systemId, templateContentDescriptionBuilder);
            }
            return new XsltSimpleTemplateFactory(bdfServer, pathConfiguration, storageUnit.getTemplateDef().getAttributes(), customExtractionDef, templates);
        } catch (TransformerConfigurationException tce) {
            LogUtils.handleTransformerException(ERROR_CATEGORY, tce, systemId, templateContentDescriptionBuilder);
            throw new CompilationException();
        }

    }

}
