/*
 * @(#)WebBeanImpl.java
 *
 * Copyright 1999-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.jdeveloper.html;

import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

/**
 * Implements the base methods for a Web Bean.
 *
 **/
public class WebBeanImpl implements WebBean
{
	protected	HttpSession				session;
	protected	HttpServletRequest	request;
	protected	HttpServletResponse	response;
   protected   PrintWriter				out;
   protected   ServletContext			application;
   protected   PageContext          page;
   protected   boolean              bUsedInTag = false;
   
	public WebBeanImpl()
	{
	}
	
   /**
   * Initializes this Web Bean object to
   * access the important objects of the JSP: application, session,
   * request, response, and out. This implementation of <TT>initialize()</TT>
   * specifies a <TT>PrintWriter</TT> rendering object. This version of <tt>initialize()</tt>
   * is designed for use in servlets.
   * <p>
   * @param application    the JSP page's ServletContext.
   * @param session        the JSP page's HttpSession.
   * @param request        the JSP page's HttpServletRequest.
   * @param response       the JSP page's HttpServletResponse.
   * @param out            the PrintWriter to render to.
   */
	public void  initialize(ServletContext application, HttpSession session,
                           HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws Exception
	{
		this.application = application;
		this.session = session;
		this.request = request;
		this.response = response;
		this.out = out;

      internalInitialize();
	}

   public void initialize(PageContext page) throws Exception
	{
      this.page = page;
      
      initialize(page.getServletContext(), page.getSession(), (HttpServletRequest) page.getRequest(),
                 (HttpServletResponse) page.getResponse(), new PrintWriter(page.getOut()));
	}

   /**
   * Initializes this Web Bean object to
   * access the important objects of the JSP: application, session,
   * request, response, and out. This implementation of <TT>initialize()</TT>
   * specifies a <TT>JspWriter</TT> rendering object. This version of <tt>initialize()</tt>
   * is designed for use in JSP pages.
   * <p>
   * @param application    the JSP page's ServletContext
   * @param session        the JSP page's HttpSession
   * @param request        the JSP page's HttpServletRequest
   * @param response       the JSP page's HttpServletResponse
   * @param out            the JspWriter to render to
   */	
	public void initialize(ServletContext application, HttpSession session , HttpServletRequest request,
                           HttpServletResponse response, JspWriter out ) throws Exception
	{
      initialize(application, session, request,response, new PrintWriter(out));
	}

   /**
   * Internal initialize.
   * This method should be overriden by any WebBean needing to initialize some internal data
   * after all the base class member have been initialize properly.
   */
   public void internalInitialize() throws Exception
   {
   }

  /**
  * <b>Internal:</b> <em>Applications should not use this method.</em>
  * <p>
  * Returns the name of the cookie associated with the JSP page's
  * <tt>HttpServletRequest</tt>.
  * <p>
  * @param sName name of the cookie
  **/
  public String   getCookie(String sName)
	{
		if(request == null)
			return null;

		String sCookie = null;

		if(request.getCookies() != null)
		{
			Cookie[] cookies = request.getCookies();

			for(int i =  0 ; i < cookies.length ; i++)
			{
				if(sName.equalsIgnoreCase(cookies[i].getName()))
				{
					sCookie = cookies[i].getValue();
					return sCookie;
				}
			}
		}
            
		return sCookie;	
	}

   public PrintWriter getOut()
   {
      return out;
   }

   public HttpServletRequest getRequest()
   {
      return request;
   }
   
   public Object getRequestVariable(String sName)
   {
      return getRequestVariable(page, request, sName);
   }
   
   static public Object getRequestVariable(PageContext pageCtx, HttpServletRequest req, String sName)
   {
      Object obj = null;

      if (pageCtx != null)
      {
        // Might need a findAttribute here because of the jsp include case
        obj = pageCtx.getAttribute(sName);
      }
      else if (req != null)
      {
         obj = req.getAttribute(sName);
      }
      
      return obj;
   }

   public void setRequestVariable(String sName, Object obj)
   {
      setRequestVariable(page, request, sName, obj);
   }
   
   static public void setRequestVariable(PageContext pageCtx, HttpServletRequest req, String sName, Object obj)
   {
      if (pageCtx != null)
      {
         pageCtx.setAttribute(sName, obj);
      }
      else if (req != null)
      {
         req.setAttribute(sName, obj);
      }
   }
   
   public void initBeanForJS(int libFlag)
   {
      out.print(initBeanForJS(page, request, libFlag, null));
   }

   public void initBeanForJS(int libFlag, String NLSFormat)
   {
      out.print(initBeanForJS(page, request, libFlag, NLSFormat));
   }
   
   static public String initBeanForJS(PageContext pageCtx, HttpServletRequest req, int libFlag, String NLSFormat)
   {
      int missingLib = 0;
      int currentFlag = 0;

      libFlag |= JSUtilitiesLib; // Always included the cabo_utilities library

      Object libInfo = null;

      libInfo = getRequestVariable(pageCtx, req, JS_LIBRARIES);

      if (libInfo == null)
      {
         missingLib = libFlag;
      }
      else
      {
         currentFlag = ((Integer)libInfo).intValue();

         // If everything needed is already set, nothing to do
         if ((currentFlag & libFlag) == libFlag)
         {
            return "";
         }

         missingLib = ~currentFlag & libFlag;
      }

      StringBuffer buff = new StringBuffer();
      if ((missingLib & JSUtilitiesLib) != 0)
      {
         generateScriptSrc(buff, "cabo_utilities.js");
         buff.append("<script LANGUAGE=\"javascript\">\n");
         buff.append("image_dir=\"");
         buff.append(WebBean.defaultCaboBase);
         buff.append("/\"+image_dir;\n");
         buff.append("jslib_dir=\"");
         buff.append(WebBean.defaultCaboBase);
         buff.append("/\"+jslib_dir;\n");
         buff.append("</script>\n");
      }

      if ((missingLib & JSTableConstructLib) != 0)
      {
         generateScriptSrc(buff, "table_constructor.js");
      }

      if ((missingLib & JSTreeConstructLib) != 0)
      {
         generateScriptSrc(buff, "tree_constructor.js");
      }

      if ((missingLib & JSDataConstructLib) != 0)
      {
         generateScriptSrc(buff, "data_constructor.js");
      }

      if ((missingLib & JSToolbarConstructorLib) != 0)
      {
         generateScriptSrc(buff, "toolbar_constructor.js");
      }

      if ((missingLib & JSCalendarConstructorLib) != 0)
      {
         generateScriptSrc(buff, "calendar_constructor.js");

         if (NLSFormat != null)
         {
            buff.append("<script language=\"javascript\">\n");
            buff.append("NLSformat = \"");
            buff.append(NLSFormat);
            buff.append("\";\n");
            buff.append("</script>\n");
         }
      }

      if ((missingLib & JSModalPageConstructorLib) != 0)
      {
         generateScriptSrc(buff, "modal_page_constructor.js");
      }

      if ((missingLib & JSButtonConstructorLib) != 0)
      {
         generateScriptSrc(buff, "button_constructor.js");
      }

      if ((missingLib & JSContainerConstructorLib) != 0)
      {
         generateScriptSrc(buff, "container_constructor.js");
      }

      libInfo = new Integer(currentFlag | libFlag);
      setRequestVariable(pageCtx, req, JS_LIBRARIES, libInfo);

      return buff.toString();
   }
	
	static protected void generateScriptSrc(StringBuffer buff, String libName)
   {
      buff.append("<script src=\"");
      buff.append(WebBean.defaultCaboBase);
      buff.append("/jslib/");
      buff.append(libName);
      buff.append("\" language=\"javascript\"></script>\n");
   }
   
   public String getUniqueName(String rootName)
   {
      int      id;
      //Integer  storedId = (Integer) session.getValue(request.toString() + JS_NAMEID);

      Integer  storedId = (Integer)this.getRequestVariable(JS_NAMEID);

      if (storedId == null)
      {
         id = 0;
      }
      else
      {
         id = storedId.intValue() + 1;
      }

      storedId = new Integer(id);
      setRequestVariable(JS_NAMEID, storedId);
      
      return rootName + storedId.toString();
   }
   
   /**
	*	Renders the Web Bean's contents to the output stream.
	*/
	public void render() throws Exception 
	{
		render(out);
	}

	/**
	*	Renders the Web Bean's contents to the specified PrintWriter.
	* <p>
	*	@param out the PrintWriter to render to.
	*/
	public void	render(PrintWriter outp)
	{
	 
	}	
}
