/*-
 * ~~~~~~licensing~~~~~~
 * object-producing-resources-support
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.producer.resources.processors;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import javax.xml.transform.ErrorListener;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;

import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
import net.sf.saxon.s9api.XsltTransformer;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.core.producer.resources.EntaxyResourceProducingProcessor;

@Deprecated(since = "1.10", forRemoval = true)
// @Component (service = EntaxyResourceProducingProcessor.class, immediate = true)
public class XSLTSaxonResourceProcessor implements EntaxyResourceProducingProcessor {

    public static final String PROP_SOURCE = "source";
    public static final String PROP_PARAMETERS = "parameters";

    private static final Logger log = LoggerFactory.getLogger(XSLTSaxonResourceProcessor.class);

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    EntaxyResourceService entaxyResourceService;

    @Override
    public String getName() {
        return "saxon";
    }

    @Override
    public Object process(Object value, Map<String, Object> properties) throws Exception {

        log.info("SAXON :: processing [{}]", value);

        if (value == null)
            return value;

        String xsltLocation = properties.getOrDefault(PROP_SOURCE, "").toString();
        if (!CommonUtils.isValid(xsltLocation)) {
            log.warn("XSL not defined in [{}]", properties);
            // TODO throw exception?
            return value;
        }

        EntaxyResource resource = entaxyResourceService.getResource(xsltLocation);
        if (!resource.exists()) {
            log.warn("XSL [{}] not found, was defined in [{}]", xsltLocation, properties);
            // TODO throw exception?
            return value;
        }


        Processor processor = new Processor(false);
        XsltCompiler compiler = processor.newXsltCompiler();
        XsltExecutable stylesheet;
        StringWriter result = new StringWriter();
        try {
            compiler.setErrorListener(new ErrorListener() {

                @Override
                public void warning(TransformerException exception) throws TransformerException {
                    log.warn("SAXON COMPILER:", exception);
                }

                @Override
                public void fatalError(TransformerException exception) throws TransformerException {
                    log.error("SAXON COMPILER:", exception);
                }

                @Override
                public void error(TransformerException exception) throws TransformerException {
                    log.error("SAXON COMPILER:", exception);
                }
            });
            stylesheet = compiler.compile(new StreamSource(resource.getInputStream()));
            Serializer out = processor.newSerializer(result);
            out.setOutputProperty(Serializer.Property.METHOD, "xml");
            out.setOutputProperty(Serializer.Property.INDENT, "yes");
            XsltTransformer transformer = stylesheet.load();
            Source xml = new StreamSource(new StringReader(value.toString()));
            transformer.setSource(xml);
            transformer.setDestination(out);
            if (properties.containsKey(PROP_PARAMETERS)) {
                Object obj = properties.get(PROP_PARAMETERS);
                if (obj instanceof Map) {
                    Map<String, Object> map = (Map<String, Object>) obj;
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        transformer.setParameter(
                                new QName(entry.getKey()), new XdmAtomicValue(entry.getValue().toString()));
                    }
                }
            }
            transformer.transform();
        } catch (SaxonApiException e) {
            log.error("Error transforming [" + value.toString() + "] with [" + xsltLocation + "]", e);
            throw e;
        }
        return result.toString();
    }

}
