/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2023 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.installer.test.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.nio.file.Path;

public class StandaloneXmlUtil {

    private final Document doc;
    private XPath xPath =  XPathFactory.newInstance().newXPath();
    private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    private DocumentBuilder builder = factory.newDocumentBuilder();

    public StandaloneXmlUtil(Path serverRoot, String name) throws ParserConfigurationException, IOException, SAXException {
        doc = builder.parse(serverRoot.resolve("standalone").resolve("configuration").resolve(name).toFile());
    }

    public String getAttribute(String expression, String attrName) throws XPathExpressionException {
        NodeList nodes = (NodeList) xPath.compile(expression).evaluate(
                doc, XPathConstants.NODESET);

        if (nodes.getLength() == 0) {
            throw new RuntimeException("No nodes matched the xpath " + expression);
        }
        if (nodes.getLength() > 1) {
            throw new RuntimeException("Too many nodes matched the xpath " + expression);
        }

        final Node attr = nodes.item(0).getAttributes().getNamedItem(attrName);
        return attr == null?null:attr.getNodeValue();
    }
}
