package daruma.wfs;

// import daruma.xml.handler.XSAXDefaultHandler;
import daruma.xml.handler.XSAXDOMCreateHandler;
import daruma.xml.URI;
import daruma.xml.util.ElementUtil;
import daruma.xml.util.XMLFormatConverter;
// import daruma.xml.util.XMLParseErrorException;
// import daruma.util.ISO8601DateFormat;
// import daruma.util.LogWriter;

import daruma.storage_manager.StorageManager;
import daruma.storage_manager.StorageException;

// import daruma.geometry.CoordinateSystem;
import daruma.geometry.CoordinateSystemTransformation;
// import daruma.geometry.AffineCoordinateSystemTransformation;
import daruma.geometry.CoordinateSystemTransformationDictionary;


import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

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

import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Date;

import java.util.List;
import java.util.ArrayList;

import daruma.xml.Lexicon;


public class GetCoordinateSystemTransformationHandler
    extends XSAXDOMCreateHandler
{
    private StorageManager	storage;
    private Date		startTime;
    private Date		endTime;
    private boolean		errorOccured;
    private List<String>	errorMessages;

    public GetCoordinateSystemTransformationHandler( OutputStream out,
						     XMLReader parser,
						     boolean isTopLevelHandler,
						     StorageManager storage )
	throws SAXException
    {
	super( out, parser, isTopLevelHandler );
	super.setInhibitEndPrefixBeforeEndDocument( true );

	this.storage = storage;

	this.errorOccured = false;
	this.errorMessages = new ArrayList<String>();

	this.endTime = null;

	try
	{
	    this.startTime = this.storage.getCurrentTime();
	}
	catch( StorageException e )
	{
	    this.throwError( new SAXParseException( e.getMessage() ,
						    super.getLocator() ,
						    e ) );
	}
    }

    public void xEndDocument() throws SAXException
    {
	//
	// parse request
	//
	Element request = super.getDocumentElement();

	if ( ! request.getLocalName().equals( "GetCoordinateSystemTransformation" )
	  || ! request.getNamespaceURI().equals( URI.MISP ) )
	{
	    this.throwError( new SAXParseException
			     ( "GetCoordinateSystemTransformation in namespace "
			       + URI.MISP + " expected, found "
			       + request.getLocalName()
			       + " in namespace "
			       + request.getNamespaceURI()
			       + ".",
			       super.getLocator() ) );
	}

	if ( ElementUtil.getChildElements( request ).size() != 0 )
	{
	    System.err.println( "aaa" );

	    this.throwError( new SAXParseException
			     ( "number of child elements in "
			       + request.getLocalName()
			       + " unexpected, expected was 0." ,
			       super.getLocator() ) );

	    System.err.println( "bbb" );
	}

	System.err.println( "ccc" );

	this.printOutput();

	System.err.println( "ddd" );
    }

    private void printOutput() throws SAXException
    {
	PrintWriter out = super.getPrintWriter();

	ResponseInfo responseInfo = super.getResponse();
	Document doc = responseInfo.document;
	Element topLevelElement = ElementUtil.genElementSimple
				  ( Lexicon.MispGetCoordinateSystemTransformationResponse,
				    null, doc, responseInfo.leaf, true );
	responseInfo.setResponseToLeaf( topLevelElement );

	CoordinateSystemTransformationDictionary dic = null;
	try
	{
	    dic = storage.getCoordTransDictionary();
	}
	catch( StorageException e )
	{
	    this.throwError( new SAXParseException
			     ( "Can't retrieve coordinate system"
			       + " transformation," + e.getMessage(),
			       super.getLocator(),
			       e ) );
	}

	for ( CoordinateSystemTransformation c
		  : dic.getAllTransform().values() )
	{
	    topLevelElement.appendChild
		( this.convertToTransformElement( c, doc ) );
	}

	out.flush();

	try
	{
	    this.getOutputStream().flush();
	}
	catch( java.io.IOException  e )
	{
	    throw new SAXException( e );
	}
    }

    private Element convertToTransformElement( CoordinateSystemTransformation c,
					       Document doc )
    {
	Element transElement = doc.createElementNS( URI.MISP, "Transformation" );

	Element identifierElement = doc.createElementNS( URI.MISP, "identifier" );
	identifierElement.appendChild( doc.createTextNode( c.getIdentifier() ) );
	transElement.appendChild( identifierElement );

	Element sourceCSElement = doc.createElementNS( URI.MISP, "sourceCS" );
	Element targetCSElement = doc.createElementNS( URI.MISP, "targetCS" );
	sourceCSElement.appendChild( doc.createTextNode( c.getSourceCS().getSrsName() ) );
	targetCSElement.appendChild( doc.createTextNode( c.getTargetCS().getSrsName() ) );
	transElement.appendChild( sourceCSElement );
	transElement.appendChild( targetCSElement );

	Element transformationMethodElement = doc.createElementNS( URI.MISP, "transformationMethod" );
	transElement.appendChild( transformationMethodElement );

	Element concreteMethodNameElement = doc.createElementNS( URI.MISP, c.getTransformName() );
	transformationMethodElement.appendChild( concreteMethodNameElement );

	Element sourceDimensionsElement = doc.createElementNS( URI.MISP, "sourceDimensions" );
	Element targetDimensionsElement = doc.createElementNS( URI.MISP, "targetDimensions" );
	sourceDimensionsElement.appendChild( doc.createTextNode( Long.toString( c.getSourceDimension() ) ) );
	targetDimensionsElement.appendChild( doc.createTextNode( Long.toString( c.getTargetDimension() ) ) );
	concreteMethodNameElement.appendChild( sourceDimensionsElement );
	concreteMethodNameElement.appendChild( targetDimensionsElement );

	Element parameterElement = doc.createElementNS( URI.MISP, "parameter" );
	parameterElement.appendChild( doc.createTextNode( c.encode() ) );
	concreteMethodNameElement.appendChild( parameterElement );

	return transElement;
    }

    private void setError( String  errorMessage )
    {
	this.errorOccured = true;
	this.errorMessages.add( errorMessage );
    }

    private void throwError( SAXParseException  e ) throws SAXException
    {
	this.setError( e.getMessage() );

	Document doc;

	try
	{
	    XMLFormatConverter.print( new SOAPFaultDocumentBuilder(e).newDocument() ,
				      this.getOutputStream() );
	}
	catch( ParserConfigurationException  pe )
	{
	    throw new SAXException( pe );
	}
	catch( TransformerException  te )
	{
	    throw new SAXException( te );
	}

	throw e;
    }

}
