package com.cogix.vwf;

/*
	WhenPageReceivedGoTo
	Illustrates a class that directs the next page to show.

	Usage:
	WhenPageReceivedGoTo destinationquestion,testquestion,value,value,value
	(no value means when blank)
	Use ! in front of testquestion to mean NOT.

	Goes to the page that contains destinationquestion when the condition is true
	
	If no testquestion and values provided, acts as an unconditional Go To

	Revised 10/8/02
	Requires ViewsFlash 3.5 or later

	Uses skipToQuestion (questonname) and then returns true immediately.
*/


class WhenPageReceivedGoTo 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 onPageReceived method is called before the page is displayed,
	//	See testShouldPageBeShown class for example.

	boolean onPageReceived (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;
		String testquestion = s.length < 2 ? "" : s [1] ;
		boolean bIsNot = testquestion.length() > 0 &&	testquestion.charAt (0) == '!';
		if (bIsNot) {
			if ( testquestion.length() < 2 )
				return false;
			testquestion = testquestion.substring (1);
			}
		if ( s.length == 1 ) {	//	skip to destination unconditionally
			bSkip = true;
			}
		else {
			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 ( valuesContain ( values, s[k+2] ) )
								bSkip = true;
							}
						}
					}
				}
			}
		if ( bSkip )
			skipToQuestion (destinationquestion);
		return bSkip;
		}
    }
