package tvark.jsf;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import tvark.beans.ResultsBean;
import tvark.beans.UploadBean;

public class RedirectListener implements PhaseListener {

	private static final long serialVersionUID = -1353494411238473329L;

	public void afterPhase(PhaseEvent pEvent) {
		
	}

	public void beforePhase(PhaseEvent pEvent) {
		String viewId = pEvent.getFacesContext().getViewRoot().getViewId();
		boolean restart = false;
		if (JsfUtils.ViewId.RESULTS.equals(viewId) || JsfUtils.ViewId.RESULT_PARAMS.equals(viewId)) {
			ResultsBean rb = JsfUtils.getValue("#{resultsBean}", ResultsBean.class);
			if (rb.isEmpty()) {
				restart = true;
			}
		} else if (JsfUtils.ViewId.PARAMETERS.equals(viewId)
				|| JsfUtils.ViewId.METHOD.equals(viewId)
				|| JsfUtils.ViewId.PARAMETERS_BAYES.equals(viewId)
				|| JsfUtils.ViewId.PARAMETERS_MC.equals(viewId)
				|| JsfUtils.ViewId.PARAMETERS_SA.equals(viewId)) {
			UploadBean ub = JsfUtils.getValue("#{uploadBean}", UploadBean.class);
			if (ub.getBytes() == null) {
				restart = true;
			}
		}
		
		if (restart) {
			JsfUtils.restart();
			pEvent.getFacesContext().responseComplete();
		}
		
	}

	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

}
