/* Copyright (c) 2001, 2003, Oracle Corporation. All Rights Reserved. */
package oracle.portal.sample.v2.devguide.partnerApp;

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

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

import oracle.portal.provider.v2.PortletException;
import oracle.portal.provider.v2.http.HttpCommonConstants;
import oracle.portal.provider.v2.render.PortletRenderer;
import oracle.portal.provider.v2.render.PortletRenderRequest;
import oracle.portal.provider.v2.render.http.BaseManagedRenderer;

import oracle.webdb.utils.SimpleStringBuffer;

/**
 * <code>FlightRenderer</code> handles renditions for the Fancy Flights
 * application both in standalone mode and in a portlet context, thus
 * demonstrating the ease with which existing applications can be integrated
 * with OracleAS Portal.
 */
public class FlightRenderer extends BaseManagedRenderer
{
    // Path to the full screen version of the partner application
    private static final String APP_PATH = "/servlet/PartnerAppFlights";

    // Application params.
    private static final String ACTION = "FlightAction";
    private static final String ID = "FlightId";
    private static final String SHOWDETAILS = "details";

    // Link fragment to save generating multiple times.
    private static final String LINK_FRAGMENT = "?" + ACTION + "=" +
        SHOWDETAILS + "&" + ID + "=";

    /**
     * Performs the rendition when the Fancy Flights application is accessed
     * from the web application front end. By this stage, users will have
     * already been authenticated by <code>mod_osso</code>.
     *
     * @param req the <code>javax.servlet.http.HttpServleRequest</code> object.
     * @param res the <code>javax.servlet.http.HttpServleResponse</code>
     * object.
     */
    public void process(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        // mod_osso should be sending us the username, cry if not.
        String username = req.getRemoteUser();
        if (username == null)
        {
            throw new ServletException("Unauthenticated user");
        }


        // Grab all the necessary bits and pieces to hand off to the rendition
        // methods.
        String baseUrl = getBaseUrl(req);
        res.setContentType(PortletRenderer.TYPE_HTML);
        PrintWriter out = res.getWriter();
        String action = req.getParameter(ACTION);
        String id = req.getParameter(ID);

        //Render the flight details if we have the relevant params,
        //otherwise just render the summary pages.
        if (action != null && id != null && id.length() > 0 &&
            action.equalsIgnoreCase(SHOWDETAILS))
        {
            showDetails(username, id, out);
        }
        else
        {
            showList(username, baseUrl, out, false);
        }

    }

    /**
     * Performs the rendition when the Fancy Flights application is accessed
     * from the portlet front end.
     *
     * @param pr the
     * <code>oracle.portal.provider.v2.render.PortletRenderRequest</code> for
     * this rendition.
     */
    public void renderBody(PortletRenderRequest pr)
        throws PortletException
    {
        try
        {
            // Portal user must be strongly authenticated to use this portlet.
            if (!pr.getUser().isLoggedOn())
            {
                renderPortletAuthError(pr);
                return;
            }

            // Get the http request/response objects for this rendition.
            HttpServletRequest req = (HttpServletRequest)
                pr.getAttribute(HttpCommonConstants.SERVLET_REQUEST);
            HttpServletResponse res = (HttpServletResponse)
                pr.getAttribute(HttpCommonConstants.SERVLET_RESPONSE);

            // Grab all the necessary bits and pieces to hand off to the
            // rendition method.
            String username = pr.getUser().getName();
            String baseUrl = getBaseUrl(req);
            res.setContentType(PortletRenderer.TYPE_HTML);
            PrintWriter out = res.getWriter();

            // For the portlet version, we only render the summary page which
            // contains deep links to the flight detail pages.
            showList(username, baseUrl, out, true);
        }
        catch (IOException ioe)
        {
            throw new PortletException(ioe);
        }
    }

    /**
     * Renders the flights summary screen.
     *
     * @param user The user who is logged in.
     * @param baseUrl absolute path to the servlet for building deep links.
     * @param out output writer for output.
     */
    private void showList(String user, String baseUrl, PrintWriter out, boolean isWebProvider)
        throws IOException
    {
        if (!isWebProvider)
        {
            out.print("<HTML>");
            out.print("<HEAD>");
            out.print("<TITLE>Flights</TITLE></HEAD>");
            out.print("</HEAD>");
            out.print("<BODY>");
        }
        out.print("<font size=-2>Welcome ");
        out.print(user);
        out.print("</font><br>");
        out.print("<CENTER>");
        out.print("<center><b><font color=\"#33CCFF\"><font size=+1>");
        out.print("Flights Of Fancy</font></font></b></center>");

        out.print("<br><b><font color=\"#3366FF\"></font></b>&nbsp;");
        out.print("<table BORDER=0 CELLSPACING=2 CELLPADDING=2 ");
        out.print("WIDTH=\"100%\" >");
        out.print("<tr>");
        out.print("<td><b><font color=\"#3333FF\">Flight Num</font></b></td>");
        out.print("<td><b><font color=\"#3333FF\">From</font></b></td>");
        out.print("<td><b><font color=\"#3333FF\">To</font></b></td>");
        out.print("<td><b><font color=\"#3333FF\">Departure</font></b></td>");
        out.print("<td><b><font color=\"#3333FF\">Arrival</font></b></td>");
        out.print("</tr>");
        out.print("<tr>");
        out.print("<TD><A href=\"");
        out.print(baseUrl);
        out.print(LINK_FRAGMENT);
        out.print("123456\">");
        out.print("<font size=-1>123456</font></A></td>");
        out.print("<td><font size=-1>JFK</font></td>");
        out.print("<td><font size=-1>MIA</font></td>");
        out.print("<td><font size=-1>6:00 AM EST 12/12/2004</font></td>");
        out.print("<td><font size=-1>9:37 AM EST 12/12/2004</font></td>");
        out.print("</tr>");
        out.print("<tr>");
        out.print("<TD><A href=\"");
        out.print(baseUrl);
        out.print(LINK_FRAGMENT);
        out.print("234567\">");
        out.print("<font size=-1>234567</font></A></td>");
        out.print("<td><font size=-1>IAD</font></td>");
        out.print("<td><font size=-1>BWI</font></td>");
        out.print("<td><font size=-1>5:00 PM EST 8/22/2004</font></td>");
        out.print("<td><font size=-1>6:45 PM EST 8/22/2004</font></td>");
        out.print("</tr>");
        out.print("<tr>");
        out.print("<td><A href=\"");
        out.print(baseUrl);
        out.print(LINK_FRAGMENT);
        out.print("345678\">");
        out.print("<font size=-1>345678</font></A></td>");
        out.print("<td><font size=-1>SFI</font></td>");
        out.print("<td><font size=-1>NAT</font></td>");
        out.print("<td><font size=-1>1:25 PM PST 10/18/2004</font></td>");
        out.print("<td><font size=-1>4:37 AM EST 10/19/2004</font></td>");
        out.print("</tr>");
        out.print("<tr>");
        out.print("<td><A href=\"");
        out.print(baseUrl);
        out.print(LINK_FRAGMENT);
        out.print("456789\">");
        out.print("<font size=-1>456789</font></A></td>");
        out.print("<td><font size=-1>OCH</font></td>");
        out.print("<td><font size=-1>DIA</font></td>");
        out.print("<td><font size=-1>10:00 PM CST 2/05/2004</font></td>");
        out.print("<td><font size=-1>2:11 AM CST 2/06/2004</font></td>");
        out.print("</tr>");
        out.print("</table>");
        out.print("<center><font color=\"#33CCFF\"><font size=-2>");
        out.print("All Times and flights are subject");
        out.print("to change without notification.&nbsp; Please consult our ");
        out.print("reservations center ");
        out.print("for exact flights and times.</font></font></center>");
        out.print("</CENTER>");
        if (!isWebProvider)
        {
            out.print("</BODY>");
            out.print("</HTML>");
        }
        else
        {
            out.print("</td></tr></table>");
        }
        out.flush();
    }

    /**
     *  Displays full details about a particular flight.
     *
     *  @param user The user who is logged in.
     *  @param out output writer for output.
     *  @param id id of the flight being displayed.
     */
    private void showDetails(String user, String id, PrintWriter out)
        throws IOException
    {
        out.print("<HTML>");
        out.print("<HEAD>");
        out.print("<TITLE>Flight ");
        out.print(id);
        out.print("</TITLE></HEAD>");
        out.print("</HEAD>");
        out.print("<BODY>");
        out.print("<font size=-2>Welcome ");
        out.print(user);
        out.print("</font><br>");
        out.print("<center><b><font color=\"#33CCFF\"><font size=+1>");
        out.print("Flights Of Fancy</font></font></b></center>");
        out.print("<b><font color=\"#3333FF\">Details for ");
        out.print(id);
        out.print("</font></b>");
        out.print("<br>");
        out.print("<hr WIDTH=\"100%\">");
        out.print("<br><font color=\"#000000\"><font size=-1>");
        out.print("Flight ");
        out.print(id);
        out.print(" operated by Fancy Flying Airlines on a Wing Stream 77 Turbo Prop.");
        out.print("</font></font>");
        out.print("<blockquote><font size=-1><font color=\"#000000\">");
        out.print("Departs:&nbsp;&nbsp; </font>6:00");
        out.print("AM EST 12/12/2004 From: JFK</font>");
        out.print("<br><font size=-1>Arrives:&nbsp; 9:37 AM EST 12/12/2004");
        out.print(" At: MIA</font>");
        out.print("<br><font size=-1>Stops:&nbsp; None</font>");
        out.print("<blockquote><font size=-1>Altitude:&nbsp; 35,000ft</font>");
        out.print("<br><font size=-1>Seating:&nbsp; Coach</font>");
        out.print("<br><font size=-1>Preferences:&nbsp; Exit Row</font>");
        out.print("<br><font size=-1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        out.print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        out.print("&nbsp;&nbsp;&nbsp;&nbsp;");
        out.print("Window</font>");
        out.print("<br><font size=-1>Smoking:&nbsp; No</font>");
        out.print("<br><font size=-1>Meals:&nbsp; ");
        out.print("Breakfast / Snack</font></blockquote>");
        out.print("<font size=-1>Price:&nbsp; $875</font></blockquote>");
        out.print("<hr WIDTH=\"100%\">");
        out.print("<center><font color=\"#33CCFF\"><font size=-2>");
        out.print("All Times and flights are subject");
        out.print("to change without notification.&nbsp; Please consult ");
        out.print("our reservations center");
        out.print("for exact flights and times.</font></font></center>");
        out.print("</BODY>");
        out.print("</HTML>");
        out.flush();
    }

    /**
     * Builds the base url to the partner app.
     */
    private String getBaseUrl(HttpServletRequest req)
    {
        return new SimpleStringBuffer(50)
            .append(req.getScheme())
            .append("://")
            .append(req.getServerName())
            .append(":")
            .append(req.getServerPort())
            .append(req.getContextPath())
            .append(APP_PATH)
            .toString();
    }

    /**
     * Renders an HTML error message in the event of the user being
     * unauthenticated.
     * 
     * @param pr the <code>PortletRenderRequest</code>
     */
    private void renderPortletAuthError(PortletRenderRequest pr)
        throws IOException
    {
        pr.setContentType(PortletRenderer.TYPE_HTML);
        PrintWriter out = pr.getWriter();
        out.println("<FONT face=\"arial,helvetica\">");
        out.println("<I>Please log in to view this portlet.</I>");
        out.println("</FONT>");
        out.flush();
    }
}
