package com.cogix.vwf;

/*
	BeforePageComposedGoTo
	Illustrates a class that prevents an entire page from displaying.

	Usage:
	BeforePageComposedGoTo destinationquestion,testquestion,value,value,value
	(no value means when blank)
	Use ! in front of testquestion to mean NOT.

	Skips showign this page when the condition is true

	Revised 10/8/02
	Requires ViewsFlash 3.5 or later

	See Extensibility in the ViewsFlash documentation:
	http://www.cogix.com/viewsflash/docs?Extensible.html

*/


class BeforePageComposedGoTo extends Validator {

	//	This function is called when the survey arrives at the page containing
	//	this Custom Action.  By default, it returns false. When it returns true,
	//	the page that contains the question set in the skipToQuestion method is displayed.
	//	Note that the destination page can contain additional Custom Actions,
	//	which in turn can themselves cause further redirection.


	boolean onPageComposition (RequestParams reqx, String questionname, String spec) {
		//	Perform integrity check on all parameters first.
		//	Return false to indicate that the condition is not met.
		boolean bSkip = false;
		String [] s = Misc.cogixParse (spec, true);
		if ( s == null || s.length < 1 )
			return false;	//	do nothing

		String destinationquestion = s [0] ;
		if ( Misc.isEmpty (destinationquestion) )
			return false;

		if ( s.length < 2 ) {	//	unconditional skip
			skipToQuestion ( destinationquestion );
			return true;
			}
				
		String testquestion = s [1] ;
		boolean bIsNot = 	testquestion.charAt (0) == '!';
		if (bIsNot) {
			if ( testquestion.length() < 2 )
				return false;
			testquestion = testquestion.substring (1);
			}
		int nparams = s.length - 2;

		//	Get the values for that question.
		//	A multiple valued answer returns xx,xx,xx, so use
		//		boolean valuesContain (String values, String avalue)

		String values = getParamValue ( reqx, testquestion );
		boolean bNoValues = Misc.isEmpty (values);
		//	First try it with a single valued question.
		if ( nparams == 0 ) {	//	Test for empty or not
			bSkip = bIsNot != bNoValues;
			}
		else {
			if ( bIsNot ) {	//	See if responses don't match any of the values
				if ( bNoValues ) {
					bSkip = true;
					}
				else {
					boolean bMatch = false;
					for ( int k = 0; ! bMatch && k < nparams; k++ ) {
						if ( valuesContain ( values, s[k+2] ) )
							bMatch = true;
						}
					bSkip = ! bMatch;
					}
				}
			else {	//	See if responses match any of the values
				if ( ! bNoValues ) {
					for ( int k = 0; ! bSkip && k < nparams; k++ ) {
						//	if ( values.equals ( s[k] ) )
						if ( valuesContain ( values, s[k+2] ) )
							bSkip = true;
						}
					}
				}
			}
		if ( bSkip )
			skipToQuestion (destinationquestion);
		return bSkip;
		}
    }
