/*-
 * ~~~~~~licensing~~~~~~
 * system-commons
 * ==========
 * 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.services.runtime.interceptor;

import java.io.IOException;
import java.util.List;

import javax.xml.soap.SOAPMessage;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.model.ServiceModelUtil;
import org.apache.cxf.ws.addressing.EndpointReferenceUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import ru.entaxy.platform.services.runtime.utils.XmlParser;

public class SOAPValidateInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private static final Log LOG = LogFactory.getLog(SOAPValidateInterceptor.class);

    private final SAAJInInterceptor saajIn;
    private final XmlParser xmlParser;
    private boolean schemaValidationEnabled;

    public SOAPValidateInterceptor() {
        super(Phase.PRE_PROTOCOL);
        saajIn = new SAAJInInterceptor();
        xmlParser = new XmlParser();

        getAfter().add(SAAJInInterceptor.class.getName());
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        if (isGET(message) || !schemaValidationEnabled) {
            return;
        }
        try {
            Node body = getMessageBody((DOMSource) getSOAPMessage(message).getSOAPPart().getContent());
            if (body != null)
                validate(body, message);
            else
                throw new XMLStreamException("Can't find the tag \"Body\"");
        } catch (RuntimeException re) {
            throw re;
        } catch (Exception e) {
            throw new Fault(e);
        }
    }

    private Node getMessageBody(DOMSource source) throws XPathExpressionException {
        Node node = source.getNode().cloneNode(true);
        List<Node> nodeList = xmlParser.getNodes(node.getLastChild(), "Body");
        return !nodeList.isEmpty() ? nodeList.get(0) : null;
    }

    private void validate(Node node, SoapMessage soapMessage)
            throws IOException, SAXException, XPathExpressionException {
        Validator validator = getValidator(soapMessage);
        validator.validate(new DOMSource(getNodeForValidate(node)));
    }

    private Node getNodeForValidate(Node node) throws XPathExpressionException {
        if (schemaValidationEnabled && node.getLocalName().contains("packets")) {
            Element element = (Element) node;
            for (Node content : xmlParser.getNodes(element, "content")) {
                content.getParentNode().removeChild(content);
            }
            return element;
        }
        return node;
    }

    private Validator getValidator(SoapMessage soapMessage) {
        Service service = ServiceModelUtil.getService(soapMessage.getExchange());
        Schema schema =
                EndpointReferenceUtils.getSchema(service.getServiceInfos().get(0), soapMessage.getExchange().getBus());
        return schema.newValidator();
    }

    private SOAPMessage getSOAPMessage(SoapMessage smsg) {
        SOAPMessage soapMessage = smsg.getContent(SOAPMessage.class);
        if (soapMessage == null) {
            saajIn.handleMessage(smsg);
            soapMessage = smsg.getContent(SOAPMessage.class);
        }
        return soapMessage;
    }

    public void setSchemaValidationEnabled(boolean schemaValidationEnabled) {
        this.schemaValidationEnabled = schemaValidationEnabled;
    }
}
