package hr.com.port.ips.eracun.validation;

import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import java.math.BigDecimal;

public final class XmlEval {
    private final XPath xp = XPathFactory.newInstance().newXPath();

    public String str(Document d, String xpath) throws XPathExpressionException {
        return xp.compile(xpath).evaluate(d);
    }

    public boolean exists(Document d, String xpath) throws XPathExpressionException {
        XPathExpression ex = xp.compile(xpath);
        NodeList nl = (NodeList) ex.evaluate(d, XPathConstants.NODESET);
        return nl != null && nl.getLength() > 0;
    }

    public int count(Document d, String xpath) throws XPathExpressionException {
        XPathExpression ex = xp.compile(xpath);
        NodeList nl = (NodeList) ex.evaluate(d, XPathConstants.NODESET);
        return nl == null ? 0 : nl.getLength();
    }

    public BigDecimal dec(Document d, String xpath) throws Exception {
        String s = str(d, xpath);
        if (s == null) return BigDecimal.ZERO;
        s = s.trim();
        if (s.isEmpty()) return BigDecimal.ZERO;
        return new BigDecimal(s);
    }

    public static BigDecimal round2(BigDecimal v) {
        if (v == null) return BigDecimal.ZERO;
        return v.setScale(2, java.math.RoundingMode.HALF_UP);
    }
}
