/**
 * Copyright (c) 2018-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.utils;

import org.ow2.petals.binding.rest.config.RESTConfiguration;
import org.ow2.petals.component.framework.api.exception.PEtALSCDKException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMUtils {

    private DOMUtils() {
        // Utility class --> No constructor
    }

    public static final String getSubElementTextContent(final Element elt, final String subEltName, boolean mandatory)
            throws PEtALSCDKException {
        final Node subElement = getSubElement(elt, subEltName, mandatory);
        return subElement != null ? subElement.getTextContent() : null;
    }

    public static final Node getSubElement(final Element elt, final String subEltName, final boolean mandatory)
            throws PEtALSCDKException {
        Node subElement = null;

        final String namespaceURI = elt.getNamespaceURI();
        final NodeList subElements = elt.getElementsByTagNameNS(namespaceURI, subEltName);
        final int subElementsNb = subElements.getLength();
        if (subElementsNb == 1) {
            subElement = subElements.item(0);
        } else if (subElementsNb == 0 && mandatory) {
            // TODO: Replace by throwing the right exception, so 'subElement' can be removed
            RESTConfiguration.handleMissingMandatoryParameterError(subEltName);
        } else if (subElementsNb > 1) {
            // TODO: Replace by throwing the right exception, so 'subElement' can be removed
            RESTConfiguration.handleNotUniqueParameterError(subEltName);
        }

        return subElement;
    }

    public static final NodeList getSubElements(final Element elt, final String subEltName) {
        String namespaceURI = elt.getNamespaceURI();
        return elt.getElementsByTagNameNS(namespaceURI, subEltName);
    }

}
