package org.infohazard.maverick.flow;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;

import org.xml.sax.ContentHandler;

/**
 * This is a Decorator pattern, setting content-type on the response if defined for a transform.
 */
class TransformWithContentType implements Transform {
	protected Transform decorated;
	protected String contentType;
	
	/**
	 */
	public TransformWithContentType(Transform simpler, String contentType)
	{
		if (contentType == null)
			throw new IllegalArgumentException("Don't use this decorator without content-type");
			
		this.decorated = simpler;
		this.contentType = contentType;
	}
	 
	public TransformStep createStep(TransformContext tctx) throws ServletException
	{
		TransformStep decoratedStep = this.decorated.createStep(tctx);
		return new TransformWithContentTypeStep(decoratedStep, contentType);
	}
	
	public  class TransformWithContentTypeStep implements TransformStep {
		
		protected TransformStep decorated;
		protected String contentType;
		
		public TransformWithContentTypeStep(TransformStep simpler, String contentType) {
			if (contentType == null)
				throw new IllegalArgumentException("Don't use this decorator without content-type");
			
			this.decorated = simpler;
			this.contentType = contentType;
		}
		
		public void done() throws IOException, ServletException {
			decorated.done();
		}
		
		public Writer getWriter() throws IOException, ServletException{
			return decorated.getWriter();
		}
		
		public ContentHandler getSAXHandler() throws IOException, ServletException {
			return decorated.getSAXHandler();
		}

		public void go(Source s) throws IOException, ServletException{
			decorated.go(s);
			if (this.isLast())
				this.getResponse().setContentType(contentType);
		}
		
		public void go(Reader r) throws IOException, ServletException{
			decorated.go(r);			
			if (this.isLast())
				this.getResponse().setContentType(contentType);
		}

		public void go(String s) throws IOException, ServletException{
			decorated.go(s);			
			if (this.isLast())
				this.getResponse().setContentType(contentType);
		}

		public boolean isLast() {
			return decorated.isLast();
		}
		
		public HttpServletResponse getResponse() throws IOException, ServletException {
			return decorated.getResponse();
		}
	}
}
