/*
 * @(#)ShowCriteriaTag.java
 *
 * Copyright 2001-2002 by Oracle Corporation,
 * 500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Oracle Corporation.
 */

package oracle.jbo.html.jsp.datatags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import oracle.jbo.AttributeDef;
import oracle.jbo.JboException;
import oracle.jbo.ViewCriteriaRow;

public class ShowCriteriaTag extends BodyTagSupport
{
   protected String sDataItem;

   public ShowCriteriaTag()
   {
   }

   public void setDataitem(String sValue)
   {
      this.sDataItem = sValue;
   }

   /**
     * Process the start tag for this instance.
     *
     * The doStartTag() method assumes that all setter methods have been
     * invoked before.
     *
     * When this method is invoked, the body has not yet been invoked.
     *
     * @returns EVAL_BODY_INCLUDE if the tag wants to process body, SKIP_BODY if it
     * does ont want to process it.
     */
   public int doStartTag() throws JspException
   {
      Object obj = null;

      // Retrieve the row from the ViewCriteriaIterateTag tag if any
      ViewCriteriaIterateTag vcIterateTag = (ViewCriteriaIterateTag) findAncestorWithClass(this, ViewCriteriaIterateTag.class);

      if (vcIterateTag == null)
      {
         throw new JboException(Res.getString(Res.SHOWCRITERIA_ONLY_INSIDE_VIEWCRITERIAITERATE));
      }
      
      ViewCriteriaRow vr = vcIterateTag.getCriteriaRow();
      
      if (sDataItem == null)
      {
         AttributeDef attrDef = getAttributeDefFromParentTag(vcIterateTag.getDatasource());
         if (attrDef != null)
         {
            obj = vr.getAttribute(attrDef.getIndex());
         }
      }
      else
      {
         obj = vr.getAttribute(sDataItem);
      }
      
      if (obj != null)
      {
         try
         {
            pageContext.getOut().print(obj.toString());
         }
         catch (java.io.IOException ex)
         {
            pageContext.getServletContext().log(Res.getString(Res.IO_ERROR), ex);
            throw new JspTagException(ex.getMessage());
         }
      }

      return SKIP_BODY;
   }

   protected AttributeDef getAttributeDefFromParentTag(String sVCIDatasource)
   {
      AttributeIterateTag iter = (AttributeIterateTag) findAncestorWithClass(this, AttributeIterateTag.class);

      if (iter == null || !sVCIDatasource.equals(iter.getDataSourceName()))
      {
         throw new JboException(Res.getString(Res.NEED_DATAITEM));
      }

      return iter.getAttributeDef();
   }

   /**
     * release() called after doEndTag() to reset state
     */
   public void release()
   {
      sDataItem = null;

      super.release();
   }
}

