package daruma.wfs;

import daruma.xml.util.DOMDocumentFactory;
import daruma.util.PropertyReader;
import daruma.xml.URI;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import java.io.PrintWriter;
import java.io.StringWriter;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXParseException;


public class SOAPFaultDocumentBuilder
{
	private	SAXParseException	exception;
	private String			errorMessage;
	private static final String	STACK_TRACE = "daruma.debug.stacktrace";

	public	SOAPFaultDocumentBuilder( SAXParseException  exception )
	{
		this.exception = exception;
		this.errorMessage = exception.getMessage();
	}

	public	SOAPFaultDocumentBuilder( String  errorMessage )
	{
		this.errorMessage = errorMessage;
	}

	public	Document	newDocument()
				  throws ParserConfigurationException
	{
		Document	doc = DOMDocumentFactory.create();

		Element	envelope = doc.createElementNS( URI.SOAP_ENV ,
							"SOAP_ENV:Envelope" );
		doc.appendChild( envelope );

		Element	body = doc.createElementNS( URI.SOAP_ENV ,
						    "SOAP_ENV:Body" );
		envelope.appendChild( body );

		Element	fault = doc.createElementNS( URI.SOAP_ENV ,
						    "SOAP_ENV:Fault" );
		body.appendChild( fault );

		Element	faultcode = doc.createElementNS
					    ( URI.SOAP_ENV ,
					      "SOAP_ENV:faultcode" );
		fault.appendChild( faultcode );
		faultcode.appendChild( doc.createTextNode("SOAP_ENV:Server") );

		Element	faultstring = doc.createElementNS
					    ( URI.SOAP_ENV ,
					      "SOAP_ENV:faultstring" );
		fault.appendChild( faultstring );
		faultstring.appendChild( doc.createTextNode
					 ( this.errorMessage ) );

		Element	detail = doc.createElementNS( URI.SOAP_ENV ,
						      "SOAP_ENV:detail" );
		fault.appendChild( detail );

		Element	parseError = doc.createElementNS( URI.MISP_ERROR ,
							  "ParseError" );

		detail.appendChild( parseError );

		if ( this.exception != null )
		{
			parseError.setAttribute
				   ( "line" ,
				     Integer.toString
				       ( exception.getLineNumber() ) );

			parseError.setAttribute
				   ( "column" ,
				     Integer.toString
				       ( exception.getColumnNumber() ) );
		}

		Element	mes = doc.createElementNS( URI.MISP_ERROR ,
						   "Message" );

		Text	errorMessageNode = doc.createTextNode
					   ( this.errorMessage );

		mes.appendChild( errorMessageNode );

		parseError.appendChild( mes );

		/* create stack trace text node */
		if (this.exception != null
		    && PropertyReader.getProperty(STACK_TRACE, false)) {
			Element	traceElement	 = doc.createElementNS( URI.MISP_ERROR , "StackTrace" );
			StringWriter traceWriter = new StringWriter();
			exception.printStackTrace(new PrintWriter(traceWriter));

			Text traceText		 = doc.createTextNode(traceWriter.toString());

			traceElement.appendChild(traceText);
			parseError.appendChild(traceElement);
		}

		return( doc );
	}
}
