package com.saxonica.testdriver;

import net.sf.saxon.lib.NamespaceConstant;
import net.sf.saxon.lib.StandardErrorListener;
import net.sf.saxon.trans.XPathException;

import javax.xml.transform.TransformerException;
import java.util.HashSet;
import java.util.Set;

public class ErrorCollector extends StandardErrorListener {

    private Set<String> errorCodes = new HashSet<String>();

    @Override
    public void error(TransformerException exception) throws TransformerException {
        addErrorCode(exception);
        super.error(exception);
    }

    @Override
    public void fatalError(TransformerException exception) throws TransformerException {
        addErrorCode(exception);
        super.fatalError(exception);
    }

    /**
     * Make a clean copy of this ErrorListener. This is necessary because the
     * standard error listener is stateful (it remembers how many errors there have been)
     *
     * @param hostLanguage the host language (not used by this implementation)
     * @return a copy of this error listener
     */
    @Override
    public StandardErrorListener makeAnother(int hostLanguage) {
        return this;
    }

    private void addErrorCode(TransformerException exception) {
        if (exception instanceof XPathException) {
            String errorCode = ((XPathException) exception).getErrorCodeLocalPart();
            if (errorCode != null) {
                String ns = ((XPathException) exception).getErrorCodeNamespace();
                if (ns != null && !NamespaceConstant.ERR.equals(ns)) {
                    errorCode = "Q{" + ns + "}" + errorCode;
                }
                errorCodes.add(errorCode);
            } else {
                errorCodes.add("ZZZZ9999");
            }
        }
    }

    public Set<String> getErrorCodes() {
        return errorCodes;
    }
}