package inc.monsters.mias.workaround;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;
import javax.faces.render.Renderer; 

import org.apache.myfaces.extensions.validator.core.ExtValContext;
import org.apache.myfaces.extensions.validator.core.interceptor.AbstractRendererInterceptor;
import org.apache.myfaces.extensions.validator.core.interceptor.RendererInterceptor;
import org.apache.myfaces.extensions.validator.core.renderkit.ExtValRendererProxy;
import org.apache.myfaces.extensions.validator.core.renderkit.exception.SkipAfterInterceptorsException;
import org.apache.myfaces.extensions.validator.core.startup.AbstractStartupListener;
import org.apache.myfaces.extensions.validator.trinidad.storage.TrinidadClientValidatorStorage;
import org.apache.myfaces.extensions.validator.util.ExtValUtils;
import org.apache.myfaces.trinidad.component.core.CoreForm;

public class DevStartupListener extends AbstractStartupListener {

	private static final Class<? extends TrinidadClientValidatorStorage> STORAGE_TYPE = TrinidadClientValidatorStorage.class;
	private static final String STORAGE_NAME = TrinidadClientValidatorStorage.class.getName();

	private static final long serialVersionUID = -2437519730374570206L;

	protected void init() {
		// Work around for bug EXTVAL-77:
		ExtValContext.getContext().addGlobalProperty(ExtValRendererProxy.KEY, null, true);
		
		// Work around for issue with NPE's thrown on Trinidad client side validations.
		// This issue should be solved in the ExtVal 1.2.3 snapshot of 2010-01-03.
		ExtValContext.getContext().registerRendererInterceptor(createRollbackInterceptor());
	}

	private RendererInterceptor createRollbackInterceptor() {
		return new AbstractRendererInterceptor() {
			public void afterEncodeEnd(FacesContext facesContext, UIComponent uiComponent, Renderer wrapped)
					throws IOException, SkipAfterInterceptorsException {
				if (uiComponent instanceof CoreForm) {
					ExtValUtils.getStorage(STORAGE_TYPE, STORAGE_NAME).rollback();
				}
			}
		};
	}
}