/*
 * @(#)DataSourceTag.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.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import oracle.jbo.JboException;
import oracle.jbo.RowIterator;
import oracle.jbo.ViewObject;
import oracle.jbo.html.DataSource;

public class ViewObjectTag extends TagSupport
{
   String sViewObject;
   protected int nRangeSize;
   String sIterMode;

   public ViewObjectTag()
   {
      super();
      reset();
   }
   
   public void setName(String sViewObject)
   {
      this.sViewObject = sViewObject;
   }

   public void setRangesize(String sValue)
      throws NumberFormatException
   {
      nRangeSize = Integer.parseInt(sValue);
   }

   public void setItermode(String sValue)
   {
      this.sIterMode = sValue;
   }

   public int doStartTag() throws JspException
   {
      int index = sViewObject.indexOf('.');
      
      if (index < 0)
      {
         throw new JboException(Res.getString(Res.INCORRECT_VIEWOBJECT_DEFINITION));
      }
      
      String appName = sViewObject.substring(0, index);
      String voName = sViewObject.substring(index + 1);
      
      DataSource ds = Utils.createDataSource(pageContext, appName, voName, null, id, false);
      ViewObject vo = ds.getRowSet().getViewObject();

      // Only set the range size if the property has been set.
      if (nRangeSize != 0)
         ds.getRowSet().setRangeSize(nRangeSize);

      if (sIterMode != null)
      {
         int iterMode;

         if (sIterMode.equalsIgnoreCase("LastPagePartial"))
         {
            iterMode = RowIterator.ITER_MODE_LAST_PAGE_PARTIAL;
         }
         else if (sIterMode.equalsIgnoreCase("LastPageFull"))
         {
            iterMode = RowIterator.ITER_MODE_LAST_PAGE_FULL;
         }
         else
         {
            throw new JboException(Res.format(Res.INVALID_ITERMODE, sIterMode));
         }

         ds.getRowSet().setIterMode(iterMode);
      }
      
      // Set the attribute on the pageContext for the scriptable variable (PAGE_SCOPE because of Orion)
      pageContext.setAttribute(id, vo);
      
      // Set the attribute on the pageContext at REQUEST_SCOPE for DataSourceRef tag
      pageContext.setAttribute(id, vo, PageContext.REQUEST_SCOPE);
      
      return Tag.EVAL_BODY_INCLUDE;
   }

   private void reset()
   {
      sViewObject = null;
      nRangeSize = 0;
      sIterMode = null;
   }
   
   /**
     * release() called after doEndTag() to reset state
     */
   public void release()
   {
      super.release();
      reset();
   }

}
