package com.ejie.ab04b.util;

import java.io.Serializable;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.ejie.ab04b.exception.AB04BException;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;

/**
 * 
 * @author GFI-NORTE
 * 
 */
public class FcasNameParser implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String INICIO_XML = "<?xml version='1.0' encoding='UTF-8' ?>";

	private String xml;

	/**
	 * Instantiates a new fcas name parser.
	 * 
	 *  xml
	 *            String
	 *
	 * @param xml the xml
	 * @throws AB04BException             AB04BXmlException
	 */
	public FcasNameParser(String xml) throws AB04BException {
		try {
			if (xml.indexOf("<?") < 0) {
				this.xml = INICIO_XML + xml;
			} else {
				this.xml = xml;
			}
		} catch (Exception e) {
			throw new AB04BException(e, e.getMessage());
		}
	}

	/**
	 * Instantiates a new fcas name parser.
	 */
	public FcasNameParser() {
	}

	/**
	 * Gets the fcas desc.
	 * 
	 *  idioma
	 *            String
	 *  String
	 *
	 * @param idioma the idioma
	 * @return the fcas desc
	 */
	public String getFcasDesc(String idioma) {
		StringBuffer ret = new StringBuffer();

		try {

			DOMParser parser = new DOMParser();
			parser.parse(new InputSource(new java.io.StringReader(this.xml)));
			Document doc = parser.getDocument();

			XPath xpath = XPathFactory.newInstance().newXPath();
			// XPath Query for showing all nodes value
			XPathExpression expr = xpath
					.compile("//fcas/*/*/language[@locale='" + idioma
							+ "']/text()");

			Object result = expr.evaluate(doc, XPathConstants.NODESET);

			NodeList nodes = (NodeList) result;
			// pais/provincia
			for (int i = 0; i < nodes.getLength(); i++) {
				ret.append(nodes.item(i).getNodeValue()).append(" ");
			}

			// XPath Query for showing all nodes value
			expr = xpath.compile("//fcas/*/text()");

			result = expr.evaluate(doc, XPathConstants.NODESET);

			nodes = (NodeList) result;
			// municipio/localidad
			for (int i = 0; i < nodes.getLength(); i++) {
				ret.append(nodes.item(i).getNodeValue()).append(" ");
			}
		} catch (Exception e) {
			return "";
		}

		return ret.toString();
	}

}
