/**
 * Check different types of counts related to the count tag.
 *
 * This tag takes several optional attributes:
 *   nexted - then number of enclosing count tags that should be active
 *               note that we need to assume the name of the class...  This should really
 *               be a parameter in TestLib.tld
 */

package tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class CheckCount extends TagSupport {

    //  nested
    public void setNested(String s) {
	try {
	    nestedCount = Integer.valueOf(s);
	} catch (Exception ex) {
	    nestedCount = null;
	}
    }
    
    // startCount
    public void setStart(String s) {
	try {
	    startCount = Integer.valueOf(s);
	} catch (Exception ex) {
	    startCount = null;
	}
    }

    // endCount
    public void setEnd(String s) {
	try {
	    endCount = Integer.valueOf(s);
	} catch (Exception ex) {
	    endCount = null;
	}
    }


    // ================== Actions ====================

    // doStartTag
    public int doStartTag() {
	if (nestedCount != null) { 
	    // check for active nested tags.

	    int k = nestedCount.intValue();
	    int c = 0;
	    Count t = (Count) TagSupport.findAncestorWithClass(this, tags.Count.class);

	    while (t != null) {
		c += 1;
		t = (Count) TagSupport.findAncestorWithClass(t, tags.Count.class);
	    }

	    if (c != k) {
		throw new Error("nested count: expecting "+k+" got "+c);
	    }
	}

	if (startCount != null) {
	    // check for start tag invocations
	    int k = startCount.intValue();

	    int c = Count.getCount(pageContext, Count.DO_START_TAG_COUNTER);
	    if (k != c) {
		throw new Error("start count: expecting "+k+" got "+c);
	    }
	}

	if (endCount != null) {
	    // check for end tag invocations
	    int k = endCount.intValue();

	    int c = Count.getCount(pageContext, Count.DO_END_TAG_COUNTER);
	    if (k != c) {
		throw new Error("end count: expecting "+k+" got "+c);
	    }
	}

	return SKIP_BODY;
    }


    // private data

    private Integer nestedCount = null;
    private Integer startCount = null;
    private Integer endCount = null;
}
