/*
 * BIAdvancedToolbarServlet.java
 *
 * Copyright © 1994-2004, Oracle. All rights reserved. Oracle grants
 * you ("Licensee") a non-exclusive, royalty-free, worldwide license to use,
 * modify and redistribute this software in source and binary code form, provided
 * that (i) this copyright notice and license appear on all copies of the
 * software; (ii) Licensee does not utilize the software in a manner disparaging
 * to Oracle; and (iii) Licensee does not utilize the software in a manner that
 * violates the terms of any Licensee agreement with Oracle.
 */
package samples.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.cabo.ui.NodeUtils;
import oracle.cabo.ui.beans.form.FormBean;
import oracle.cabo.ui.beans.layout.PageLayoutBean;
import oracle.cabo.ui.beans.nav.ButtonBean;
import oracle.cabo.ui.beans.nav.PageButtonBarBean;
import oracle.cabo.ui.ServletRenderingContext;

import oracle.dss.thin.beans.BIConstants;
import oracle.dss.thin.beans.DialogListener;
import oracle.dss.thin.beans.DialogEvent;

import oracle.dss.thin.beans.dataView.ThinDataviewCommon;
import oracle.dss.thin.beans.dataView.Presentation;
import oracle.dss.thin.beans.dataView.PresentationBean;

import oracle.dss.thin.beans.pageLayout.PageLayoutUtils;
import oracle.dss.thin.beans.toolbar.ViewToolbar;
import oracle.dss.thin.beans.toolbar.ViewToolbarBean;
import oracle.dss.thin.beans.tools.BaseViewTool;
import oracle.dss.thin.beans.tools.FormatTool;
import oracle.dss.thin.beans.tools.StoplightTool;
import oracle.dss.thin.beans.tools.ViewToolEvent;
import oracle.dss.thin.beans.tools.ViewToolListener;

import oracle.dss.thin.servlet.ServletQueryParameterProvider;
import oracle.dss.thin.servlet.ServletRequestHandler;

import oracle.dss.thin.beans.gridView.ThinGridView;
import oracle.dss.thin.beans.gridViewCustomizer.FormatCustomizer;
import oracle.dss.thin.beans.gridViewCustomizer.FormatCustomizerBean;
import oracle.dss.thin.beans.gridViewCustomizer.FormatPage;



/** 
 * The main class for the BIAdvancedToolbarServlet sample. This sample extends the
 * BIPPRToolbarServlet sample.
 * <P>
 * The BIAdvancedToolbarServlet sample illustrates the following:
 * <ol>
 * <li>Using the toolbar to modify the view</li>
 * <li>Enabling partial page rendering</li>
 * <li>Enabling advanced links</li>
 * </ol>
 * <P>
 */
public class BIAdvancedToolbarServlet extends BIPPRToolbarServlet {

  // the key for storing the BIHttpSession object on the HTTP session
  private static final String BI_HTTP_SESSION_KEY = "BIAdvancedHttpSessionKey";

  // the name of the formatCustomizer
  private static final String FORMAT_CUSTOMIZER_NAME = "formatCustomizer";

  /**
   * add UIX component tree to the rootNode
   */
  protected void addContents(ServletQueryParameterProvider provider,
                             ServletRequestHandler handler,
                             ServletRenderingContext renderingContext,
                             HttpServletRequest request,
                             FormBean rootNode) throws IOException {

    switch (getCurrentPage()) {
    case PRESENTATION_PAGE:
      addPresentation(provider, handler, request, rootNode);
      break;

    case FORMAT_PAGE:
      addFormatCustomizer(renderingContext, handler, rootNode);
      break;
    }
  }

  /**
   * add FormatCustomizer and Footer to rootNode
   */
  protected void addFormatCustomizer(ServletRenderingContext context, 
                                   ServletRequestHandler handler,
                                   FormBean rootNode) throws IOException {

    Presentation presentation = (Presentation)handler.getThinBean(PRESENTATION_NAME);
    ThinDataviewCommon dataview = presentation.getView();

    if (dataview instanceof ThinGridView) {

      FormatCustomizer formatCustomizer = (FormatCustomizer)handler.getThinBean(FORMAT_CUSTOMIZER_NAME);
      if (null == formatCustomizer)
        return;

      // set format customizer's currrent page
      if (isFormatPageOverridden()) {
        formatCustomizer.setCurrentPageIndex(getFormatPage());
        clearFormatPage();
      }

      PageLayoutBean pageLayout = new PageLayoutBean();
      PageLayoutUtils.initPageLayoutBean(pageLayout, formatCustomizer);

      FormatCustomizerBean formatBean = new FormatCustomizerBean(formatCustomizer);
      pageLayout.addIndexedChild(formatBean);

      // add Page Footer (page level buttons)
      PageButtonBarBean pageButtons = new PageButtonBarBean();
      String[] events = formatCustomizer.getPageButtonEvents();

      if (events != null) {
        for (int i = 0; i < events.length; i++) {
          ButtonBean button = new ButtonBean();

          NodeUtils.setTextAndAccessKey(button, formatCustomizer.getPageButtonEventLabel(events[i]));
          button.setOnClick(formatCustomizer.getPageButtonEventOnClick(events[i]));
          pageButtons.addIndexedChild(button);
        }
      }
      pageLayout.setPageButtons(pageButtons);

      rootNode.addIndexedChild(pageLayout);
    }
  }

  /**
   * This method returns the key for storing the BIHttpSession object on the HTTP session
   *
   * @return The key for storing the BIHttpSession object on the HTTP session
   */
  protected String getHttpSessionKey() {
    return BI_HTTP_SESSION_KEY;
  }

  /**
   * Retrieves the title of the sample. Derived classes should override this
   * method to provide custom titles.
   *
   * @return The title of the sample.
   */
  protected String getSampleTitle() {
    return "BI Beans Sample - Toolbar/View Interaction with Advanced Links";
  }

  /**
   * Retrieves the description of the sample. Derived classes should override
   * this method to provide custom descriptions.
   *
   * @return The description of the sample.
   */
  protected String getSampleDescription() {
    return "This sample shows how to enable advanced links in the Stoplight " +
           "tool and the Format tool in the toolbar.";
  }

  /**
   * Initializes thin beans
   *
   * @param request An HttpServletRequest object that contains the request that
   * the client has made of the servlet.
   *
   * @throws Exception If an error is detected when the thin beans are being
   * initialized.
   */
  protected void initializeThinBeans(HttpServletRequest request) throws Exception {
    BIHttpSession biHttpSession = getBIHttpSession(request);

    ServletRequestHandler handler = biHttpSession.getServletRequestHandler();

    Presentation presentation = (Presentation) handler.getThinBean(PRESENTATION_NAME);
    if (null == presentation) {
      // create and register a presentation and toolbar
      super.initializeThinBeans(request);

      // retrieve toolbar and presentation from servlet request handler
      ViewToolbar viewToolbar = (ViewToolbar) handler.getThinBean(TOOLBAR_NAME);
      presentation = (Presentation) handler.getThinBean(PRESENTATION_NAME);

      // create and register a FormatCustomizer bean
      if (viewToolbar != null && presentation != null) {
        FormatCustomizer formatCustomizer = new FormatCustomizer();
        formatCustomizer.setThinBeanName(FORMAT_CUSTOMIZER_NAME);
        formatCustomizer.setGridView((ThinGridView)presentation.getView());
        formatCustomizer.setPartialRenderEnabled(true);
        handler.registerThinBean(formatCustomizer);

        // when Apply or Cancel is clicked at the top level of the FormatCustomizer, 
        // the servlet will render the presentation page to view the result.
        formatCustomizer.addDialogListener(new DialogAdapter(biHttpSession));

        // when Advanced links are clicked on the FormatTool or StoplightTool,
        // the servlet will render the FormatCustomizer pages 
        viewToolbar.addViewToolListener(new ViewToolAdapter(biHttpSession));

        for (int i = 0; i < viewToolbar.getChildCount(); i++) {
          Object child = viewToolbar.getChild(i);

          // enable advanced link for FormatTool and StoplightTool
          if (child instanceof FormatTool || child instanceof StoplightTool)
            ((BaseViewTool)child).setAdvancedLinksDisplayed(true);
        }
      }
    }
  }

  /**
   * Processes the View Tool event. 
   *
   * @param l The ViewToolListener for the current view. If the event is
   * VIEW_TYPE_CHANGED, it is handled by presentation bean.
   * @param e The ViewToolEvent that is broadcast by the Toolbar thin bean when
   * an action occurs on the client.
   * @param biHttpSession Provides a way to identify a user across more than
   * one page request and to store information about that user.
   */
  protected void processViewToolEvent (ViewToolListener l, ViewToolEvent e, BIHttpSession biHttpSession) {
    String action = e.getAction();

    clearFormatPage();

    // we only handle events from FormatTool and StoplightTool
    if (e.getSource() instanceof FormatTool) {

      if (BIConstants.FORMAT_CELLS_EVENT.equalsIgnoreCase(action)) {
        setFormatPage(FormatCustomizer.FORMATCELLS_PAGE);
      }
      else if (BIConstants.EXCEPTION_FORMATS_EVENT.equalsIgnoreCase(action)) {
        setFormatPage(FormatCustomizer.EXCEPTIONFORMATS_PAGE);
      }
      else if (BIConstants.CONDITIONAL_FORMAT_EVENT.equalsIgnoreCase(action)) {
        setFormatPage(FormatCustomizer.CONDITIONAL_FORMAT_PAGE);
      }
    }
    else if (e.getSource() instanceof StoplightTool) {
      if (BIConstants.EXCEPTION_FORMATS_EVENT.equalsIgnoreCase(action)) {
        setFormatPage(FormatCustomizer.EXCEPTIONFORMATS_PAGE);
      }
    }

    if (isFormatPageOverridden()) {
      // set page to be displayed
      setCurrentPage(FORMAT_PAGE);

      // retrieve the servlet request handler
      ServletRequestHandler requestHandler = (ServletRequestHandler)biHttpSession
        .getServletRequestHandler();

      FormatCustomizer formatCustomizer = (FormatCustomizer)requestHandler.getThinBean(FORMAT_CUSTOMIZER_NAME);
      if (null != formatCustomizer) {
        formatCustomizer.reset(m_formatPage);
        FormatPage page = (FormatPage)formatCustomizer.getCurrentPage();
        if (page != null)
          page.init(e.getQueryParameterProvider());
      }
    }
  }

  /**
   * Implements the ViewToolListener interface.
   */
  public class ViewToolAdapter implements ViewToolListener {
    protected BIHttpSession m_biHttpSession = null;

     /**
      * Creates a ViewToolAdapter object.
      *
      * @param biHttpSession the BIHttpSession object.
      */
    public ViewToolAdapter(BIHttpSession biHttpSession) {
      m_biHttpSession = biHttpSession;
    }

     /**
      * Handles a View Tool event
      *
      * @param e the ViewToolEvent.
      */
    public void handleViewToolEvent(ViewToolEvent e) {
      processViewToolEvent(this, e, m_biHttpSession);
    }
  }

  /**
   * Implements the DialogListener interface.
   */
  public class DialogAdapter implements DialogListener {
    protected BIHttpSession m_biHttpSession = null;

     /**
      * Creates a DialogEventAdapter object.
      *
      * @param biHttpSession the BIHttpSession object.
      */
    public DialogAdapter(BIHttpSession biHttpSession) {
      m_biHttpSession = biHttpSession;
    }

     /**
      * Handles a Dialog event
      *
      * @param e the DialogEvent.
      */
    public void handleDialogEvent(DialogEvent e) {
      int eventType = e.getType();

      if (eventType == DialogEvent.DIALOG_COMPLETED ||
          eventType == DialogEvent.DIALOG_CANCELED) {
        setCurrentPage(PRESENTATION_PAGE);
      }
    } 
  }    

  public void setCurrentPage(int page) {
    m_currentPage = page;
  }

  public int getCurrentPage() {
    return m_currentPage;
  }

  public void setFormatPage(int page) {
    m_formatPage = page;
  }

  public int getFormatPage() {
    return m_formatPage;
  }

  protected boolean isFormatPageOverridden() {
    return (getFormatPage() != FormatCustomizer.UNKNOWN_PAGE);
  }

  protected void clearFormatPage() {
    setFormatPage(FormatCustomizer.UNKNOWN_PAGE);
  }

  protected int m_formatPage = FormatCustomizer.UNKNOWN_PAGE;

  // possible values for the current display page (m_currentPage)
  protected static final int PRESENTATION_PAGE = 0;
  protected static final int FORMAT_PAGE = 1;

  protected int m_currentPage = PRESENTATION_PAGE;
  protected int m_pageCount = 0;
}
