/*
 * FlightDispatch.java 1.00 27-Feb-2001
 *
 * Copyright 2000-2001 by Oracle Corporation
 * 500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A.
 * All rights reserved.
 */
package oracle.portal.sample.v2.devguide.externalApp;

import java.io.*;
import java.util.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import oracle.portal.utils.v2.*;
import oracle.portal.provider.v2.*;
import oracle.portal.provider.v2.render.*;
import oracle.portal.provider.v2.http.HttpCommonConstants;

public class FlightDispatch
{
    private String mServletPath;

    private static final String ACTION = "FlightAction";
    private static final String ID = "FlightId";
    private static final String USERNAME = "FlightUser";
    private static final String PASSWORD = "FlightPass";
    private static final String SHOWDETAILS = "details";
    private static final String PERFORMLOGIN = "performlogin";
    private static final String FLIGHTDEST = "FlightDest";

    /**
     *  Constructor
     */
    public FlightDispatch(String servletPath)
    {
        mServletPath = servletPath;
    }//FlightDispatch Constructor


    /**
     *  Construct URLs for links to the detail screen.
     *
     *  Construct URLs based on weather or not we are running as
     *  as a web provider.
     *
     *  @param id  is the id number of the flight.
     *  @param servletURL absolute path to the servlet.
     *  @param pr a <code>PortletRenderRequest</code>, if this is this a response
     *  from a web provider.
     *
     *  @return the final link
     */
    private String buildURL(String id, String servletURL, PortletRenderRequest pr)
        throws IOException
    {
        StringBuffer server = new StringBuffer(servletURL);
        server.append("?");
        server.append(ACTION);
        server.append("=");
        server.append(SHOWDETAILS);
        server.append("&");
        server.append(ID);
        server.append("=");
        server.append(id);

        String hrefValue = null;
        if (pr != null)
        {
            String loginURL=pr.getRenderContext().getLoginServerURL();
            String str1 = PortletRendererUtil.parameterizeLink(loginURL,
                                                               "p_url_name=" + FLIGHTDEST);

            hrefValue = PortletRendererUtil.parameterizeLink(str1,
                                                             "p_url_value=" + 
                                                             PortletRendererUtil.encodeParameter(server.toString(), pr));
        }
        else
        {
            hrefValue = server.toString();
        }
        return hrefValue;
    }


    /**
     *  Display the flight list screen.
     *
     *  @param user   The user who is logged in.
     *  @param servletURL absolute path to the servlet.
     *  @param out  output writer for output.
     *  @param pr a <code>PortletRenderRequest</code>, if this is this a response
     *  from a web provider.
     */
    private void showList(String user, String servletURL, Writer out, PortletRenderRequest pr)
        throws IOException
    {
        if (pr == null)
        {
            out.write("<HTML>");
            out.write("<HEAD>");
            out.write("<TITLE>Flights</TITLE></HEAD>");
            out.write("<BODY>");
        }
        out.write("<table BORDER=1 WIDTH=\"100%\" ><tr><td>");
        out.write("<font size=-1>Welcome "+user+"</font><br>");
        out.write("<CENTER>");
        out.write("<center><b><font color=\"#33CCFF\"><font size=+1>");
        out.write("Flights Of Fancy</font></font></b></center>");

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

    }//showList

    /**
     *  Display the details screen.
     *
     *  @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, Writer out)
        throws IOException
    {
        out.write("<HTML>");
        out.write("<HEAD>");
        out.write("<TITLE>Flight "+ id+"</TITLE></HEAD>");
        out.write("<BODY>");
        out.write("<font size=-1>Welcome "+user+"</font><br>");
        out.write("<center><b><font color=\"#33CCFF\"><font size=+1>");
        out.write("Flights Of Fancy</font></font></b></center>");
        out.write("<b><font color=\"#3333FF\">Details for "+id+"</font></b>");
        out.write("<br>");
        out.write("<hr WIDTH=\"100%\">");
        out.write("<br><font color=\"#000000\"><font size=-1>");
        out.write("Flight "+id+" operated by Fancy");
        out.write("Flying Airlines on a Wing Stream 77 Turbo Prop.</font></font>");
        out.write("<blockquote><font size=-1><font color=\"#000000\">");
        out.write("Departs:&nbsp;&nbsp; </font>6:00");
        out.write("AM EST 12/12/2002 From: JFK</font>");
        out.write("<br><font size=-1>Arrives:&nbsp; 9:37 AM EST 12/12/2002");
        out.write(" At: MIA</font>");
        out.write("<br><font size=-1>Stops:&nbsp; None</font>");
        out.write("<blockquote><font size=-1>Altitude:&nbsp; 35,000ft</font>");
        out.write("<br><font size=-1>Seating:&nbsp; Coach</font>");
        out.write("<br><font size=-1>Preferences:&nbsp; Exit Row</font>");
        out.write("<br><font size=-1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        out.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        out.write("&nbsp;&nbsp;&nbsp;&nbsp;");
        out.write("Window</font>");
        out.write("<br><font size=-1>Smoking:&nbsp; No</font>");
        out.write("<br><font size=-1>Meals:&nbsp; ");
        out.write("Breakfast / Snack</font></blockquote>");
        out.write("<font size=-1>Price:&nbsp; $875</font></blockquote>");
        out.write("<hr WIDTH=\"100%\">");
        out.write("<center><font color=\"#33CCFF\"><font size=-2>");
        out.write("All Times and flights are subject");
        out.write("to change without notification.&nbsp; Please consult ");
        out.write("our reservations center");
        out.write("for exact flights and times.</font></font></center>");

        out.write("</BODY>");
        out.write("</HTML>");
        out.flush();
        out.close();
    }

    /**
     *  This method receives the requests, and makes the proper calls.
     *
     *  This is the main routine in the case of the standalone servlet.
     *  When direct servlet calls are made, they are processed here.  Based
     *  upon the parameters received, and the state of login, different screens
     *  are displayed.
     *
     *  @param req Servlet request object.
     *  @param res Servlet response object.
     */
    public void process(HttpServletRequest req,
                        HttpServletResponse res)
        throws IOException
    {
        ApplicationLogin login = new ApplicationLogin(req,res);
        String action = req.getParameter(ACTION);
        String id = req.getParameter(ID);
        String username = req.getParameter(USERNAME);
        String password = req.getParameter(PASSWORD);
        String flightDest = req.getParameter(FLIGHTDEST);

        String user = null;
        StringBuffer server = new StringBuffer();
        //Set up the server string to be passed around.
        server.append(req.getScheme()).append("://")
            .append(req.getServerName());
        int serverPort = req.getServerPort();

        // set the content type to html
        res.setContentType("text/html");
        // If it's the defualt port, don't append the port
        // number
        if (( serverPort != 80) && (serverPort!= 433))
        {
            server.append(":")
                .append(serverPort);
        }

        // Add the fully-qualified servlet path
        String contextPath = req.getContextPath();
        server.append(contextPath);
        if(mServletPath != null)
        {
            server.append(mServletPath);
        }
        else
        {
            server.append(req.getServletPath());
        }

        //Begin processing by checking the login status.
        if (login.isLoggedIn())
        {
            user = login.getUser();
            if (action != null &&
                action.equalsIgnoreCase(SHOWDETAILS) &&
                id != null &&
                !id.equals(""))
            {
                showDetails(user,id,res.getWriter());
            }
            else if (action != null &&
                     action.equalsIgnoreCase(PERFORMLOGIN) &&
                     username != null && password != null)
            {
                if (flightDest == null)
                {
                    login.performLogin(username, password, server.toString(), contextPath);
                }
                else
                {
                    login.performLogin(username, password, flightDest, contextPath);
                }
            }
            else
                showList(user,server.toString(),res.getWriter(), null);
        }//if loggedin
        else
        {
            if (action != null &&
                action.equalsIgnoreCase(PERFORMLOGIN))
            {
                if (flightDest == null)
                {
                    login.performLogin(username,password,server.toString(), contextPath);
                }
                else
                {
                    login.performLogin(username,
                                       password,
                                       flightDest,
                                       contextPath);
                }
            }
            else
            {
                login.drawLogin(server.toString());
            }
        }
    }

    /**
     *  This method receives the requests, and makes the proper calls.
     *
     *  This is the main routine in the case of the provider impementation.
     *  When calls from portal are made, they are processed here.  Based
     *  upon the parameters received, and the state of login, different screens
     *  are displayed.
     *
     *  @param pr Render request object
     */
    public void process
        (
         PortletRenderRequest pr
         )
        throws IOException
    {
        ApplicationLogin login = new ApplicationLogin(pr);
        String name = null;
        String username = null;
        String password = null;
        String action = null;
        String id = null;
        PrintWriter out = pr.getWriter("text/html");

        String user = pr.getUser().getName();
        StringBuffer server = new StringBuffer();
        server.append(pr.getScheme()).append("://")
            .append(pr.getServerName());
        int serverPort = pr.getServerPort();

        if (( serverPort != 80) && (serverPort!= 433))
        {
            server.append(":")
                .append(serverPort);
        }

        // Add the fully-qualified servlet path
        HttpServletRequest req = (HttpServletRequest)pr.getAttribute(HttpCommonConstants.SERVLET_REQUEST);
        server.append(req.getContextPath());
        server.append(mServletPath);

        if (login.isLoggedIn())
        {
            user = login.getUser();
            showList(user, server.toString(), out, pr);
        }//if loggedin
        else
        {
            out.println("Your session with this application has expired. " +
                        "Please log back in to portal to establish a new session.");
        }
            
    }

}//FlightDispatch
