package oracle.jbo.html.jsp.datatags;

import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;

import oracle.jbo.html.jsp.datatags.Utils;
import oracle.jbo.html.DataSource;
import oracle.jbo.JboException;


public class SetWhereClauseParamTag extends TagSupport 
{
   protected String     sDataSource;
   protected DataSource ds;
   protected int        index;
   protected String     sValue;

   public SetWhereClauseParamTag()
   {
      reset();
   }

   public void setIndex(String sValue)
      throws java.lang.NumberFormatException
   {
      index = Integer.parseInt(sValue);
   }

   public void setValue(String sValue)
   {
      if (sValue != null)
      {
         sValue.trim();
         if (sValue.length() == 0)
         {
            sValue = null;
         }
      }
         
      this.sValue = sValue;
   }

   public void setDatasource(String sDataSource)
   {
      this.sDataSource = sDataSource;
   }

   public int doStartTag() throws JspException
   {
      // If the datasource id is defined, used it to retrieve the datasource
      if (sDataSource != null)
      {
         ds = Utils.getDataSourceFromContext(pageContext, sDataSource);
      }
      // Otherwise try to find a datasourceExt in the hierachy.
      else
      {
         DataSourceTag dataSourceTag = (DataSourceTag) TagSupport.findAncestorWithClass(this, DataSourceTag.class);

         if (dataSourceTag == null)
         {
            throw new JboException(Res.getString(Res.MISSING_DATASOURCE));
         }

         ds = dataSourceTag.getDataSource();
      }

      ds.getRowSet().setWhereClauseParam(index, sValue);

      return SKIP_BODY;
   }

   // Use by the constructor and the release method to reset the member variable values
   private void reset()
   {
      index = -1;
      sValue = null;
   }
   
   /**
     * release() called after doEndTag() to reset state
     */
   public void release()
   {
      reset();
      super.release();
   }
}