/********************************************************************
 *  Oracle JDeveloper
 *  Copyright (c) 1997, 1999, Oracle Corporation. All rights reserved.
 ********************************************************************/


package oracle.jdeveloper.html;

import java.io.*;

/**
 * A class representing the base root class used by all HTML
 * generation classes. Is is never instantiated, it simply
 * provides some common services shared by all derived
 * classes.
 *
 * @author  Juan Oropeza
 * @version PUBLIC
 *
 */

public abstract class HTMLElement
{
   protected   String   sClassName = "clsElement";

   abstract public void render(PrintWriter out) throws Exception;

   public String getAsString()
   {
      String sRet = "error";

      try
      {
         ByteArrayOutputStream outstrm = new ByteArrayOutputStream();
         PrintWriter pw = new PrintWriter(outstrm);


         render(pw);

         pw.flush();
         pw.close();

         sRet = outstrm.toString();
      }
      catch(Exception ex)
      {
         ex.printStackTrace();
      }

      return sRet;
   }
   /**
   *	@return the CSS class name for this element
   */
   public String getCSSClassName()
   {
      return sClassName;
   }

   /**
   *	Sets the CSS class name for this element.
   */
   public void setCSSClassName(String sClass)
   {
      sClassName = sClass;
   }
   
   /**
    *  Fixes a URL value that is to be embedded in an HTML page.
    *
    *  URL values need to be fixed up prior to being embedded in an
    * HTML page. This function replaces all 'special' characters so
    * that they don't become altered when they are subsequently passed
    * back to the HTTP server. 
    */
   static public String  fixFieldValueForHTML(String sValue)
   {
      StringBuffer  sBuffer = new StringBuffer();
      int           nIndex;
      int           nLength;

      if(sValue == null)
         return null;
       
      nLength =  sValue.length();
       
      // replace all ' with ''
      for(nIndex = 0 ; nIndex < nLength ; nIndex++)
      {
         if(sValue.charAt(nIndex) == '+')
         {
            sBuffer.append("%2B");
         }
         else if(sValue.charAt(nIndex) == ' ')
         {
            sBuffer.append("%20");
         }
         else if(sValue.charAt(nIndex) == '?')
         {
            sBuffer.append("%3f");
         }
         else if(sValue.charAt(nIndex) == '/')
         {
            sBuffer.append("%2f");
         }
         else
            sBuffer.append(sValue.charAt(nIndex));
      }

      return sBuffer.toString();
   }   

   /**
    *  Renders the object to the HTML output stream.
    *
    *  Render is the key function that needs to be implemented by
    *  all derived classes. It basically renders the HTML representation
    *  of the given HTML object.
    */
   public void render(OutputStream out) throws Exception
   {
      PrintWriter   pw = new PrintWriter(out);
       
      render(pw);
   }

}