package com.ejie.ab04b.util;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;

/**
 * Clase que utiliza SAX para cambiar el namespace de un xml al que se le
 * indique en el constructor de la clase
 * 
 * @author Aitor_Roncero
 * 
 */
public class NamespaceFilter extends XMLFilterImpl {

	private String usedNamespaceUri;
	private boolean addNamespace;

	// State variable
	private boolean addedNamespace = false;

	/**
	 * Constructor de la clase.
	 * 
	 *  namespaceUri            namespace con el que se quiere modificar algunos elementos del
	 *            xml
	 *  addNamespace            indica si se ha de cambiar o no el namespace
	 *
	 * @param namespaceUri the namespace uri
	 * @param addNamespace the add namespace
	 */
	public NamespaceFilter(String namespaceUri, boolean addNamespace) {
		super();

		if (addNamespace) {
			this.usedNamespaceUri = namespaceUri;
		} else {
			this.usedNamespaceUri = "";
		}
		this.addNamespace = addNamespace;
	}

	/* (non-Javadoc)
	 * @see org.xml.sax.helpers.XMLFilterImpl#startDocument()
	 */
	@Override()
	public void startDocument() throws SAXException {
		super.startDocument();
		if (this.addNamespace) {
			this.startControlledPrefixMapping();
		}
	}

	/* (non-Javadoc)
	 * @see org.xml.sax.helpers.XMLFilterImpl#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
	 */
	@Override()
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		if (PlateaGenericEnum.contieneValor(localName)) {
			super.startElement(this.usedNamespaceUri, localName, qName, atts);
		} else {
			super.startElement(uri, localName, qName, atts);
		}
	}

	/* (non-Javadoc)
	 * @see org.xml.sax.helpers.XMLFilterImpl#endElement(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override()
	public void endElement(String arg0, String arg1, String arg2)
			throws SAXException {
		super.endElement(this.usedNamespaceUri, arg1, arg2);
	}

	/**
	 * Start controlled prefix mapping.
	 *
	 * @throws SAXException             Excepción
	 */
	private void startControlledPrefixMapping() throws SAXException {

		if (this.addNamespace && !this.addedNamespace) {
			// We should add namespace since it is set and has not yet been
			// done.
			super.startPrefixMapping("", this.usedNamespaceUri);

			// Make sure we dont do it twice
			this.addedNamespace = true;
		}
	}

}
