package wk.mailingservices.satori;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import wk.foundation.ToStringBuilderFactory;

import com.webobjects.foundation.NSMutableDictionary;

public class SatoriZipTaskSaxHandler extends DefaultHandler {

	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(SatoriZipTaskSaxHandler.class);

	private boolean isInResponseFields = false;
	private String currentElement;
	private StringBuilder currentCharacterDataInsideElement;

	@Override
	public void startElement(String namespaceURI, String localName,
		            String qualifiedName, Attributes atts) throws SAXException {
		if (log.isDebugEnabled()) {
			ToStringBuilder b = ToStringBuilderFactory.createPreferredToStringBuilderStyle("startElement: ");
			b.append("namespaceURI", namespaceURI);
			b.append("localName", localName);
			b.append("qualifiedName", qualifiedName);
			b.append("atts", atts);

			log.debug(b.toString());
		}

		if (isInResponseFields) {
			currentElement = localName;
			currentCharacterDataInsideElement = new StringBuilder();
		} //~ if (isInResponseFields)

		// We have hit the beginning of the ResponseFields element
		// Keep this last in this method
		if (localName.equalsIgnoreCase("ResponseFields")) {
			isInResponseFields = true;
		} //~ if (localName.equalsIgnoreCase("ResponseFields"))

	}

	@Override
	public void endElement(String namespaceURI, String localName,
		            String qualifiedName) throws SAXException {
		if (log.isDebugEnabled()) {
			ToStringBuilder b = ToStringBuilderFactory.createPreferredToStringBuilderStyle("endElement: ");
			b.append("namespaceURI", namespaceURI);
			b.append("localName", localName);
			b.append("qualifiedName", qualifiedName);

			log.debug(b.toString());
		}

		// Keep this at start of the method
		if (localName.equalsIgnoreCase("ResponseFields")) {
			isInResponseFields = false;
		} //~ if (localName.equalsIgnoreCase("ResponseFields"))

		if (isInResponseFields) {
			String currentValue = currentCharacterDataInsideElement.toString();
			if (StringUtils.equalsIgnoreCase(localName, currentElement)) {
				// End if current element
				if (StringUtils.isNotBlank(currentElement) && StringUtils.isNotBlank(currentValue)) {
					// The XML Reader already unescapes XML entities inside elements, so we do not need to unescape
					// even though we escaped element content when constructing the request
					
					// Added to results
					results().setObjectForKey(currentValue, currentElement);
					if (log.isDebugEnabled())
						log.debug("Added result '" + currentCharacterDataInsideElement + "' for field '" + currentElement);
				} //~ if (!StringUtils.isEmpty(currentElement) && !StringUtils.isEmpty(currentValue))

				currentElement = null;
				currentCharacterDataInsideElement = null;
			} //~ if (StringUtils.equalsIgnoreCase(localName, currentElement))
		} //~ if (isInResponseFields)
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (isInResponseFields && currentElement != null) {

            for (int i = start; i < start+length; i++) {
                currentCharacterDataInsideElement.append(ch[i]);
            }

            if (log.isDebugEnabled())
				log.debug("characters: currentValue = " + currentCharacterDataInsideElement + "; currentElement = " + currentElement);
		} //~ if (condition)
	}

	private NSMutableDictionary<String, String> _results;

	/** @return what */
	public NSMutableDictionary<String, String> results() {
		if ( _results == null ) {
			_results = new NSMutableDictionary<String, String>();
		}
		return _results;
	}
}
