/*-
 * ~~~~~~licensing~~~~~~
 * base-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.base.support.xml;

import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/*
 * import net.sf.saxon.TransformerFactoryImpl; import net.sf.saxon.lib.NamespaceConstant;
 */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import ru.entaxy.platform.base.support.CommonUtils;

public class CommonXMLUtils {
    public static final Logger log = LoggerFactory.getLogger(CommonXMLUtils.class);
    private static final String XML_SAX_EXTERNAL_GENERAL_ENTITIES =
            "http://xml.org/sax/features/external-general-entities";
    private static final String XML_SAX_EXTERNAL_PARAMETER_ENTITIES =
            "http://xml.org/sax/features/external-parameter-entities";

    // GETTING DOCUMENT

    public static Document getDocument(URL url) throws Exception {
        return getDocument(url.openStream());
    }

    public static Document getDocument(InputStream stream) throws Exception {
        return getDocument(false, stream);
    }

    public static Document getDocument(boolean namespaceAware, InputStream stream) throws Exception {
        InputSource is = new InputSource(stream);
        return getDocument(namespaceAware, is);
    }

    public static Document newDocument(boolean namespaceAware) throws Exception {
        return getDocument(namespaceAware, (File) null);
    }

    public static Document getDocument(boolean namespaceAware, String path) throws Exception {
        return getDocument(namespaceAware, CommonUtils.isValid(path) ? (new File(path)) : null);
    }

    public static Document getDocument(boolean namespaceAware, File file) throws Exception {
        DocumentBuilderFactory dbf = newDocumentBuilderFactoryInstance();

        dbf.setNamespaceAware(namespaceAware);
        DocumentBuilder db = dbf.newDocumentBuilder();
        if (file != null)
            return db.parse(file);
        else
            return db.newDocument();

    }

    public static Document newDocument() throws Exception {
        return newDocument(false);
    }

    public static Document getDocument(String path) throws Exception {
        return getDocument(false, path);
    }

    public static Document parseString(boolean namespaceAware, String xmlData) throws Exception {
        InputSource is = new InputSource(new StringReader(xmlData));
        return getDocument(namespaceAware, is);
    }

    public static Document getDocument(InputSource source) throws Exception {
        return getDocument(false, source);
    }

    public static Document getDocument(boolean namespaceAware, InputSource source) throws Exception {
        DocumentBuilderFactory factory = newDocumentBuilderFactoryInstance();

        factory.setNamespaceAware(namespaceAware);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document d = builder.parse(source);
        return d;
    }

    public static DocumentBuilderFactory newDocumentBuilderFactoryInstance() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        // Disable external entities declarations
        try {
            factory.setFeature(XML_SAX_EXTERNAL_GENERAL_ENTITIES, false);
            factory.setFeature(XML_SAX_EXTERNAL_PARAMETER_ENTITIES, false);
        } catch (ParserConfigurationException e) {
            // log.warn(e.getMessage(), e);
            log.warn(e.getMessage());
        }

        return factory;
    }

    public static TransformerFactory newTransformerFactoryInstance() {
        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        // Disable external entities declarations
        try {
            transformerFactory.setFeature(XML_SAX_EXTERNAL_GENERAL_ENTITIES, false);
            transformerFactory.setFeature(XML_SAX_EXTERNAL_PARAMETER_ENTITIES, false);
        } catch (TransformerConfigurationException e) {
            // log.warn(e.getMessage(), e);
            log.warn(e.getMessage());
        }
        return transformerFactory;
    }

    public static String doc2string(Document doc) throws Exception {
        // set up a transformer
        TransformerFactory transfac = newTransformerFactoryInstance();

        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        String xmlString = sw.toString();

        return xmlString;
    }

    public static String node2string(Node node) throws Exception {
        TransformerFactory transfac = newTransformerFactoryInstance();

        Transformer t = transfac.newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter sw = new StringWriter();
        t.transform(new DOMSource(node), new StreamResult(sw));
        return sw.toString();
    }

    // SAVING DOCUMENT
    public static void saveDocument(Document doc, String path) throws Exception {
        File file = new File(path);
        saveDocument(doc, file);
    }

    public static void saveDocument(Document doc, File file) throws Exception {
        DOMSource source = new DOMSource(doc);
        Result result = new StreamResult(file);

        TransformerFactory transfac = newTransformerFactoryInstance();

        Transformer xformer = transfac.newTransformer();
        xformer.transform(source, result);
    }

    // MARSHAL
    public static void jaxbMarshal(JAXBContext context, JAXBElement<?> object, Node node) throws Exception {
        Marshaller m = context.createMarshaller();
        jaxbMarshall(m, object, node);
    }

    public static void jaxbMarshall(Marshaller m, JAXBElement<?> object, Node node) throws Exception {
        if (node == null || node.getNodeType() != Node.ELEMENT_NODE)
            throw new IllegalArgumentException("Node is not Element");
        m.marshal(object, node);
    }

    public static String jaxbMarshall(JAXBContext context, JAXBElement<?> object) throws Exception {
        String result = null;

        Marshaller m = context.createMarshaller();
        StringWriter sw = new StringWriter();
        m.marshal(object, sw);
        result = sw.toString();

        return result;
    }

    // UNMARSHAL
    /**
     * 
     * @param context
     * @param node
     * @param classMap
     * @return
     * @throws Exception
     */

    public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node,
            HashMap<String, Class<? extends Object>> classMap) throws Exception {
        Unmarshaller um = context.createUnmarshaller();
        return jaxbUnmarshall(um, node, classMap);
    }

    public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node,
            HashMap<String, Class<? extends Object>> classMap) throws Exception {
        if (node.getNodeType() != Node.ELEMENT_NODE)
            throw new IllegalArgumentException("Node is not Element");
        String nodeName = node.getNodeName();
        String[] s = nodeName.split(":");
        nodeName = s[s.length - 1];
        Class<?> objectClass = classMap.get(nodeName.toLowerCase());
        if (objectClass == null)
            throw new IllegalArgumentException("Node name " + nodeName + " not found in map " + classMap.toString());
        Object obj = um.unmarshal(node, objectClass);
        return (JAXBElement<?>) obj;
    }

    public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Document doc) throws Exception {
        JAXBContext context = JAXBContext.newInstance(
                type.getPackage().getName(), type.getClassLoader());
        NodeList list = doc.getChildNodes();
        Node node = null;
        for (int i = 0; i < list.getLength(); i++) {
            if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {
                node = list.item(i);
                break;
            }
        }
        if (node == null)
            throw new Exception("Root element not found in document");
        return jaxbUnmarshall(context.createUnmarshaller(), node, type);
    }

    public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Node node) throws Exception {
        JAXBContext context = JAXBContext.newInstance(
                type.getPackage().getName(), type.getClassLoader());
        return jaxbUnmarshall(context.createUnmarshaller(), node, type);
    }

    public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node, Class<?> type) throws Exception {
        return jaxbUnmarshall(context.createUnmarshaller(), node, type);
    }

    public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node, Class<?> type) throws Exception {
        Object obj = um.unmarshal(node, type);
        return (JAXBElement<?>) obj;
    }

    // XSLT
/*	
	public static void transform(URL input, URL xslt, Result result) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",TransformerFactoryImpl.class.getClassLoader());

Source xsltS = new StreamSource(xslt.openStream());
Transformer transformer = factory.newTransformer(xsltS);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");

InputStream is = input.openStream();

Source inputS = new StreamSource(is);
transformer.transform(inputS, result);
		
	}
*/
    // XPath

/*	public static XPath createXPath() throws Exception {
		XPathFactory factory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON, 
				"net.sf.saxon.xpath.XPathFactoryImpl", net.sf.saxon.xpath.XPathFactoryImpl.class.getClassLoader());
		XPath xpath = factory.newXPath();
return xpath;
	}
	
	public static String getStringXPathResult(org.w3c.dom.Node node, String expression) throws Exception {
		XPath xpath = createXPath();
		XPathExpression expr = xpath.compile(expression);
		Object result = expr.evaluate(node, XPathConstants.STRING);
		if (result == null)
			return null;
		return result.toString();
	}*/
}
