/*  
 * Copyright 2006 T. Mark Cyster 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 */
package com.fortpoint.taglib.template;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.BodyContent;

/**
 * Defines a template section - to be used only inside an apply tag
 *
 * @author Offermatica Inc (T.M Cyster)
 */
public class SectionTag extends BodyTagSupport {
  private String name = "";

  public void setName(String name) {
    this.name = name;
  }

  public int doStartTag() throws JspException {
    if (name == null || name.equals("")) {
      throw new JspException("Section tag must have a name");
    }

    getTemplate().putFragmentsUptoSection(name, pageContext);

    return EVAL_BODY_INCLUDE;
  }


  public int doEndTag() throws JspException {
    BodyContent bodyContent = getBodyContent();

    return EVAL_PAGE;
  }

  private Template getTemplate() throws JspException {
    ApplyTag applyTag;
    try {
      applyTag = (ApplyTag) getParent();
    } catch (ClassCastException e) {
      throw new JspException(
        "A Template Section tag can only be used in a Template Apply Tag");
    }

    if (applyTag.getTemplate() == null) {
      throw new JspException(
        "Parent apply tag doesn't have a template applicator");
    }

    return applyTag.getTemplate();
  }
}
