/*
 * @(#)CreateViewObjectTag.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 java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
import oracle.jbo.ApplicationModule;
import oracle.jbo.JboException;
import oracle.jbo.RowSet;
import oracle.jbo.ViewObject;
import oracle.jbo.common.ampool.ApplicationModuleRef;

public class CreateViewObjectTag extends BodyTagSupport
{
   String amId;            // Required param
   String sViewObject;     // Required param
   String sQuery = null;
   int    nRangeSize = 0;

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

   public void setAppid(String amId)
   {
      this.amId = amId;
   }

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

   /**
   * doEndTag
   * @return int
   * @exception javax.servlet.jsp.JspException
   */
   public int doEndTag() throws JspException
   {
      if (this.bodyContent != null)
      {
         StringWriter strout = new StringWriter();

         try
         {
            bodyContent.writeOut(strout);
         }
         catch (java.io.IOException ex)
         {
            throw new JspTagException(ex.getMessage());
         }

         this.sQuery = strout.toString();

         ApplicationModuleRef amRef = Utils.getAMRefFromContext(pageContext, amId);
         ApplicationModule am = amRef.useApplicationModule();
         
         ViewObject view = am.findViewObject(sViewObject);

         if (view != null)
         {
            // remove the old instance
            view.remove();
         }

         view = am.createViewObjectFromQueryStmt(sViewObject, sQuery);

         if (view == null)
         {
            throw new JboException(Res.format(Res.UNABLE_TO_CREATE_VO, sViewObject));
         }

         RowSet rs = view.getRowSet();

         if (nRangeSize != 0)
         {
            rs.setRangeSize(nRangeSize);
         }

      }
      
      return Tag.EVAL_PAGE;
   }

   /**
    * doStartTag
    * @return int
    * @exception javax.servlet.jsp.JspException
    */
   public int doStartTag() throws JspException
   {
      return BodyTag.EVAL_BODY_AGAIN;
   }

   /**
      * release() called after doEndTag() to reset state
      */
   public void release()
   {
      super.release();

      sQuery = null;
      nRangeSize = 0;
   }
}

