/**
 * Copyright (c) 2007-2012 EBM WebSourcing, 2012-2024 Linagora
 * 
 * This program/library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or (at your
 * option) any later version.
 * 
 * This program/library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program/library; If not, see http://www.gnu.org/licenses/
 * for the GNU Lesser General Public License version 2.1.
 */
package org.ow2.petals.binding.rest.config;

import static org.ow2.petals.binding.rest.RESTConstants.SUParameter.MAPPING;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;

import org.ow2.petals.binding.rest.RESTConstants.CommonServicesParameter;
import org.ow2.petals.binding.rest.config.incoming.OperationBuilder;
import org.ow2.petals.binding.rest.utils.DOMUtils;
import org.ow2.petals.component.framework.api.exception.PEtALSCDKException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.ebmwebsourcing.easycommons.json.Xml2JsonConverter;
import com.ebmwebsourcing.easycommons.xml.QNameHelper;

import de.odysseus.staxon.json.JsonXMLConfig;

public abstract class RESTSUConfiguration {

    protected static final NodeList getSUOperationMappingNodes(final List<Element> elements)
            throws PEtALSCDKException {

        final int elementsNb = elements.size();
        int eltIndex = 0;
        Element mappingElt = null;
        while (eltIndex < elementsNb && mappingElt == null) {
            final Element elt = elements.get(eltIndex);
            if (elt != null && elt.getLocalName().equals(MAPPING)) {
                mappingElt = elt;
            }
            eltIndex++;
        }

        final NodeList operationNodes;
        if (mappingElt != null) {
            final String namespaceURI = mappingElt.getNamespaceURI();
            operationNodes = mappingElt.getElementsByTagNameNS(namespaceURI, OperationBuilder.XML_TAG_NAME);
        } else {
            // TODO: Replace by throwing the right exception, so 'operationNodes' can be removed
            RESTConfiguration.handleMissingMandatoryParameterError(MAPPING);
            operationNodes = null;
        }

        return operationNodes;
    }

    public static JsonXMLConfig getInputJsonXMLConfig(final Element operationElt) throws PEtALSCDKException {

        final String virtRootStr = DOMUtils.getSubElementTextContent(operationElt,
                CommonServicesParameter.HTTP_BODY_FROM_JSON_VIRTUAL_ROOT, false);
        final QName virtRoot;
        if (virtRootStr != null) {
            // we don't want to use the namespace of the jbi document!
            virtRoot = QNameHelper.fromString(operationElt, virtRootStr, XMLConstants.NULL_NS_URI);
        } else {
            virtRoot = null;
        }

        final String multiplePiStr = DOMUtils.getSubElementTextContent(operationElt,
                CommonServicesParameter.HTTP_BODY_FROM_JSON_MULTIPLE_PI, false);
        final Optional<Boolean> multiplePi;
        if (multiplePiStr != null) {
            multiplePi = Optional.of(Boolean.parseBoolean(multiplePiStr));
        } else {
            multiplePi = Optional.empty();
        }

        final NodeList namespaceMappingNodes = DOMUtils.getSubElements(operationElt,
                CommonServicesParameter.NAMESPACE_MAPPING);
        final Map<String, String> namespaceMappings = new HashMap<>(namespaceMappingNodes.getLength());
        for (int i = 0; i < namespaceMappingNodes.getLength(); i++) {
            final Node namespaceMappingNode = namespaceMappingNodes.item(i);
            if (namespaceMappingNode instanceof Element) {
                final String prefix = ((Element) namespaceMappingNode)
                        .getAttribute(CommonServicesParameter.NAMESPACE_MAPPING_PREFIX);
                if (prefix == null || prefix.trim().isEmpty()) {
                    throw new PEtALSCDKException(
                            "The prefix of a namespace mapping declaration is missing or empty !!");
                }

                final String uri = namespaceMappingNode.getTextContent();
                if (uri == null || uri.trim().isEmpty()) {
                    throw new PEtALSCDKException("The URI of a namespace mapping declaration is missing or empty !!");
                }

                namespaceMappings.put(prefix, uri);
            } else {
                throw new PEtALSCDKException(CommonServicesParameter.NAMESPACE_MAPPING + " is not an XML element !!");
            }
        }

        return Xml2JsonConverter.buildConfiguration(virtRoot, multiplePi, namespaceMappings);
    }
}
