package com.intellier;

import com.primix.tapestry.BasePage;
import com.primix.tapestry.IPage;
import com.primix.tapestry.IRequestCycle;
import com.primix.tapestry.IResponseWriter;
import com.primix.tapestry.PageRedirectException;
import com.primix.tapestry.RequestCycleException;
import java.lang.reflect.*;

/**
 * @author adam
 *
 * To change this generated comment edit the template variable "typecomment":
 * Window>Preferences>Java>Templates.
 * To enable and disable the creation of type comments go to
 * Window>Preferences>Java>Code Generation.
 */
public class SecurePage extends BasePage {

	private Method isLoggedIn;

	/**
	 * @see AbstractPage#beginResponse(IResponseWriter, IRequestCycle)
	 */
	public void beginResponse(IResponseWriter arg0, IRequestCycle cycle)
		throws RequestCycleException {

		cycle.getRequestContext().getResponse().setHeader("Pragma", "no-cache");
		cycle.getRequestContext().getResponse().setHeader(
			"Cache-Control",
			"no-cache");
		cycle.getRequestContext().getResponse().setHeader(
			"Expires",
			new java.util.Date().toString());

		super.beginResponse(arg0, cycle);
	}

	/**
	 * @see com.primix.tapestry.AbstractPage#validate(IRequestCycle)
	 */
	public void validate(IRequestCycle cycle) throws RequestCycleException {
		Object visit = getVisit();
		if (isLoggedIn == null) {
			try {
				isLoggedIn = visit.getClass().getMethod("isLoggedOn", null);
			} catch (Exception e) {
				throw new RequestCycleException(
					"Cannot determine log in state",
					this);
			}
		}
		Object result = null;
		try {
			result = isLoggedIn.invoke(visit, null);
		} catch (IllegalAccessException e) {
			throw new RequestCycleException(
				"Cannot determine log in state",
				this);
		} catch (InvocationTargetException e) {
			throw new RequestCycleException(
				"Cannot determine log in state",
				this);
		}
		if (result instanceof Boolean) {
			if (!((Boolean) result).booleanValue()) {
				throw new PageRedirectException("Home");
			}
		}
	}

	protected void gotoPage(IRequestCycle cycle, String pageName)
		throws RequestCycleException {
		IPage page = cycle.getPage(pageName);
		page.validate(cycle);
		cycle.setPage(page);
	}
}