package com.rixty.util;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.wicket.protocol.http.WebResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class NonEncodingWebResponse extends WebResponse {
	private static final Logger log = LoggerFactory.getLogger(NonEncodingWebResponse.class);
	private final HttpServletResponse httpServletResponse;
	
	public NonEncodingWebResponse(WebResponse original) {
		super(original.getHttpServletResponse());
		httpServletResponse = original.getHttpServletResponse();
	}
	
	@Override
	public CharSequence encodeURL(CharSequence url) {
		return url;
	}

	@Override
	public void redirect(String url)
	{
		if (!redirect)
		{
			if (httpServletResponse != null)
			{
				// don't encode url; otherwise our jsessionid will be added to an external url
				// url = httpServletResponse.encodeRedirectURL(url);
				try
				{
					if (httpServletResponse.isCommitted())
					{
						log.error("Unable to redirect to: " + url +
							", HTTP Response has already been committed.");
					}

					if (log.isDebugEnabled())
					{
						log.debug("Redirecting to " + url);
					}

					if (isAjax())
					{
						/*
						 * By reaching this point, make sure the HTTP response status code is set to
						 * 200, otherwise wicket-ajax.js will not process the Ajax-Location header
						 */
						httpServletResponse.addHeader("Ajax-Location", url);

						// safari chokes on empty response. so we should always output at least a
						// "-"

						/*
						 * usually the Ajax-Location header is enough and we do not need to the
						 * redirect url into the response, but sometimes the response is processed
						 * via an iframe (eg using multipart ajax handling) and the headers are not
						 * available because XHR is not used and that is the only way javascript has
						 * access to response headers.
						 */
						httpServletResponse.getWriter().write(
							"<ajax-response><redirect>" + url + "</redirect></ajax-response>");

						configureAjaxRedirect();
					}
					else
					{
						httpServletResponse.sendRedirect(url);
					}
					redirect = true;
				}
				catch (IOException e)
				{
					log.warn("redirect to " + url + " failed: " + e.getMessage());
				}
			}
		}
		else
		{
			log.info("Already redirecting to an url current one ignored: " + url);
		}
	}

	
}
