// Copyright (c) 2002 Oracle Corporation

package oracle.portal.sample.v2.devguide.feedback;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import java.util.ResourceBundle;
import java.util.Locale;

import oracle.portal.provider.v2.ProviderSession;
import oracle.portal.provider.v2.render.http.BaseManagedRenderer;
import oracle.portal.provider.v2.render.PortletRenderRequest;
import oracle.portal.provider.v2.render.http.ServletPortletRenderRequest;
import oracle.portal.provider.v2.http.HttpCommonConstants;
import oracle.portal.provider.v2.render.PortletRendererUtil;
import oracle.portal.provider.v2.render.http.HttpPortletRendererUtil;
import oracle.webdb.provider.v2.utils.http.ProviderRequestWrapper;
import oracle.portal.provider.v2.PortletException;
import oracle.portal.provider.v2.personalize.NameValuePersonalizationObject;
import oracle.webdb.utils.SimpleStringBuffer;
import oracle.portal.sample.v2.devguide.feedback.resource.FeedbackBundle;
import oracle.portal.log.LogManager;

/**
 * The sample feedback portlet's edit mode renderer.
 */
public class EditRenderer extends BaseManagedRenderer
{
  //
  // These strings are used to pass a parameter with the edit mode portlet
  // render request indicating that instead of rendering normal edit mode
  // the feedback parameters passed with the request should be submitted
  // to the database.
  //
  public static final String CUSTOMER_NAME_PARAM   = "customerName";
  public static final String COMPANY_NAME_PARAM    = "companyName";
  public static final String FEEDBACK_TEXT_PARAM   = "text";
  public static final String SUBMIT_FEEDBACK_PARAM = "submitFeedback";
  public static final String SUBMIT_FEEDBACK_VALUE = "1";

  // The data source path used by JDBC
  private static final String DATA_SOURCE_PATH = "jdbc/feedback";

  /**
   * Renders the portlet in edit mode.
   */
  public void renderBody(PortletRenderRequest prr) throws PortletException
  {
    try
    {
      // Check for the invalidate_cache parameter in the original request. If
      // it is found, send the invalidation request and redirect back to the
      // calling page.
      String submitFeedbackParam = prr.getParameter(
            PortletRendererUtil.portletParameter(prr, SUBMIT_FEEDBACK_PARAM));
      if (submitFeedbackParam != null &&
            submitFeedbackParam.equals(SUBMIT_FEEDBACK_VALUE))
      {
        String feedbackResult = submitFeedback(prr);

        ProviderSession session = prr.getSession();
        if (session != null)
        {
          String paramName = PortletRendererUtil.portletParameter(prr, 
                                  "feedbackResult");
          session.setAttribute(paramName, feedbackResult);
        }
        else
        {
          LogManager.debug("Feedback portlet edit renderer - no session found");
        }

        // Feedback submit has completed. Redirect to show mode.
        HttpPortletRendererUtil.sendRedirect(prr, 
            prr.getRenderContext().getBackURL());
      }
      else
      {
        // Get the customization data object.
        NameValuePersonalizationObject data = (NameValuePersonalizationObject)PortletRendererUtil.getEditData(prr);

        // Normal customisation functions
        //
        // Retrieve the name of the parameter used to represent the user
        // action taken on the edit form. This name was assigned by
        // RenderManager but can be overridden by the portlet developer.
        String actionParam = PortletRendererUtil.getEditFormParameter(prr);
                
        // Now retrieve the value of that action parameter.
        String action = prr.getParameter(actionParam);
                
        // If the action was non null, then we have to save our newly
        // customized data. Otherwise, we have to render the edit form.
        if (action != null)
        {

          data.setPortletTitle(prr.getParameter("hw_title"));
          PortletRendererUtil.submitEditData(prr, data);
        }
        else
        {
          // Get non-customizable text.
          Locale locale = prr.getPortletReference().getLocale();
          ResourceBundle bundle =
              prr.getPortletDefinition().getResourceBundle(locale);

          String titleLabel = bundle.getString(FeedbackBundle.TITLE_LABEL_KEY);

          // Get a writer for the edit form.
          PrintWriter out = prr.getWriter();

          out.println("<table BORDER CELLSPACING=0>");
          out.println("<tr><td>");
          out.println(titleLabel);
          out.println("</td><td><INPUT TYPE=\"text\" ");
          out.println("SIZE=\"40\" MAXLENGTH=\"60\" ");
          out.println("NAME=\"hw_title\" VALUE=\"");
          out.println(data.getPortletTitle());
          out.println("\"/></td></tr>");
        }                
      }
    }
    catch (IOException ioe)
    {
      throw new PortletException(ioe);
    }
  }

  /**
   * Submits the feedback to the database.
   */
  private String submitFeedback(PortletRenderRequest prr)
  {
    // Get non-customizable text.
    Locale locale = prr.getPortletReference().getLocale();
    ResourceBundle bundle =
        prr.getPortletDefinition().getResourceBundle(locale);

    Connection connection = null;
    PreparedStatement preparedStatement = null;

    // Initialize return string 
    SimpleStringBuffer retStr = new SimpleStringBuffer(200);

    try
    {
      String customerName = prr.getParameter(
                PortletRendererUtil.portletParameter(prr, CUSTOMER_NAME_PARAM));
      String companyName  = prr.getParameter(
                PortletRendererUtil.portletParameter(prr, COMPANY_NAME_PARAM));
      String feedbackText = prr.getParameter(
                PortletRendererUtil.portletParameter(prr, FEEDBACK_TEXT_PARAM));

      InitialContext ic = new InitialContext();
      DataSource dataSource = (DataSource)ic.lookup(DATA_SOURCE_PATH);

      // Get a connection from the pool
      connection = dataSource.getConnection();

      // Prepare the INSERT statement for the FEEDBACK_DETAILS table
      SimpleStringBuffer queryString = new SimpleStringBuffer("INSERT INTO FEEDBACK_DETAILS");
      queryString.append("( CUSTOMER_NAME, COMPANY_NAME, ");
      queryString.append("FEEDBACK_TEXT) values (?, ?, ? ) ");
      preparedStatement =
          connection.prepareStatement(queryString.toString());

      preparedStatement.setString(1, customerName);
      preparedStatement.setString(2, companyName);
      preparedStatement.setString(3, feedbackText);

      // Execute the Prepared statement to check number of rows inserted
      if (preparedStatement.executeUpdate() == 1)
      {
        retStr.append(bundle.getString(FeedbackBundle.FBSAVED_KEY));
      }
      else
      {
        retStr.append(bundle.getString(FeedbackBundle.FBNOTSAVED_KEY));
      }
    }
    catch (SQLException e )
    {
      retStr.append(bundle.getString(FeedbackBundle.SQLERR_KEY));
      retStr.append(": ");
      retStr.append(e);
    }
    catch(NamingException ne)
    {
      retStr.append(bundle.getString(FeedbackBundle.DATASRC_KEY));
      retStr.append(DATA_SOURCE_PATH);
      retStr.append(": ");
      retStr.append(ne.getMessage());
    }
    finally
    {
      try
      {
        if (preparedStatement != null)
        {
          preparedStatement.close();
        }
        if (connection != null) 
        {
          connection.close();
        }
      }
      catch (SQLException e)
      {
        // Replace contents of result string with sql error message.
        retStr.setLength(0);
        retStr.append(bundle.getString(FeedbackBundle.SQLERR_KEY));
        retStr.append(": ");
        retStr.append(e);
      }
      return retStr.toString();
    }
  }
}
