/*-
 * ~~~~~~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.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.osgi.service.component.annotations.Component;
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.lib.StandardErrorListener;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.esb.resources.EntaxyResourceURLFactory;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.xml.CommonXMLUtils;
import ru.entaxy.platform.core.producer.resources.EntaxyResourceProducingProcessor;

@Component(service = EntaxyResourceProducingProcessor.class, immediate = true)
public class XSLTResourceProcessor implements EntaxyResourceProducingProcessor {

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

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

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

    @Reference(cardinality = ReferenceCardinality.MANDATORY, target = "(provider=entaxy-resources)")
    URIResolver xslResourceUriResolver;

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

    @Override
    public Object process(Object value, Map<String, Object> properties) throws Exception {
        log.debug("XSLT :: 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;
        }
        TransformerFactory factory = CommonXMLUtils.newTransformerFactoryInstance();

        StreamSource xslt =
                new StreamSource(resource.getInputStream(), EntaxyResourceURLFactory.getGlobalUrl(resource).toString());
        Transformer transformer;
        try {

            transformer = factory.newTransformer(xslt);
            transformer.setURIResolver(xslResourceUriResolver);
            if (transformer.getErrorListener() == null)
                transformer.setErrorListener(new StandardErrorListener());
            ((StandardErrorListener) transformer.getErrorListener()).setLogger(new net.sf.saxon.lib.Logger() {
                @Override
                public void println(String text, int level) {
                    // info 0; warn 1; error 2; fatal 3;
                    switch (level) {
                        case 0:
                            log.info(text);
                            break;
                        case 1:
                            log.warn(text);
                            break;
                        default:
                            log.error(text);
                    }
                }

                @Override
                public StreamResult asStreamResult() {
                    return null;
                }
            });
        } catch (TransformerConfigurationException e) {
            log.error("Error creating transformer for [" + xsltLocation + "]", e);
            throw e;
        }

        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(entry.getKey(), entry.getValue());
                }
            }
        }

        Source xml = new StreamSource(new StringReader(value.toString()));
        StringWriter result = new StringWriter();
        try {
            transformer.transform(xml, new StreamResult(result));
        } catch (TransformerException e) {
            log.error("Error transforming [" + value.toString() + "] with [" + xsltLocation + "]", e);
            throw e;
        }

        return result.toString();
    }

}
