package org.seasar.jsf.application;

import java.io.IOException;
import java.util.Locale;

import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.seasar.framework.container.S2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
import org.seasar.jsf.ViewRenderer;
import org.seasar.jsf.util.FacesContextUtil;
import org.seasar.jsf.util.RequestUtil;

public class S2ViewHandler extends ViewHandler {

	private ViewHandler originalViewHandler;
	
	private ViewRenderer viewRenderer;

	public S2ViewHandler(ViewHandler originalViewHandler) {
		this.originalViewHandler = originalViewHandler;
	}

	public Locale calculateLocale(FacesContext context) {
		return originalViewHandler.calculateLocale(context);
	}

	public String calculateRenderKitId(FacesContext context) {
		return originalViewHandler.calculateRenderKitId(context);
	}

	public String getActionURL(FacesContext context, String viewId) {
		return originalViewHandler.getActionURL(context, viewId);
	}

	public String getResourceURL(FacesContext context, String path) {
		return originalViewHandler.getResourceURL(context, path);
	}

	public UIViewRoot createView(FacesContext context, String viewId) {
		return originalViewHandler.createView(context, viewId);
	}

	public void renderView(FacesContext context, UIViewRoot viewRoot)
			throws IOException {

		HttpServletRequest request = FacesContextUtil.getRequest(context);
		String path = RequestUtil.getPath(request);
		if (path.equals(viewRoot.getViewId())) {
			HttpServletResponse response = FacesContextUtil.getResponse(context);
			getViewRenderer().renderView(path, request, response);
		} else {
			ExternalContext extContext = context.getExternalContext();
			extContext.dispatch(viewRoot.getViewId());
		}
	}
	
	protected ViewRenderer getViewRenderer() {
		if (viewRenderer == null) {
			S2Container container = SingletonS2ContainerFactory.getContainer();
			viewRenderer = (ViewRenderer) container.getComponent(ViewRenderer.class);
		}
		return viewRenderer;
	}

	public UIViewRoot restoreView(FacesContext context, String viewId) {
		return originalViewHandler.restoreView(context, viewId);
	}

	public void writeState(FacesContext context) throws IOException {
		originalViewHandler.writeState(context);
	}	
}