import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;

import HTML.*;
import ConnectionPool.*;

/*
    This servlet displays a full list of the current items
    in the shopping basket.  It takes the current title ids
    found in the shopping basket and does a database lookup
    to complete the object.  It then displays the list of
    titles.  It also presents a button to complete the order
    or clear the contents of the shopping basket.  This
    servlet inherits its doGet() method from CatalogServlet.
*/

public class ShoppingBasketServlet extends CatalogServlet {

  // Method Name: init()
  // Purpose: This is the default init() method.
  public void init(ServletConfig config)
    throws ServletException {
    
    super.init(config);
  }

  // Method Name: selectByTitleId()
  // Purpose: This method takes the passed in title_id
  // and performs a database lookup returning the ResultSet
  // from the query.
  private ResultSet selectByTitleId(int title_id)
    throws Exception {

    Connection con = null;
    ConnectionPool pool = null;
    ResultSet rs = null;

    try {

      // Get a reference to the ConnectionPool from the Global
      // ServletContext
      ServletContext context = getServletContext();
      if ( context == null ) {

        throw new ServletException("Could not get a reference" +
          " to the ServletContext");
      }
      pool =(ConnectionPool)
        context.getAttribute("CONNECTION_POOL");

      if ( pool == null ) {

        throw new ServletException("Could not get reference" +
          " to the CONNECTION_POOL");
      }
      // Get a connection from the ConnectionPool
      con = pool.getConnection();
      if ( con == null ) {

        throw new ServletException("Could not get reference" +
          " Connection.");
      }
      if ( con != null ) {

        // Create the statement
        Statement statement = con.createStatement();

        // Use the created statement to SELECT the DATA
        // FROM the Titles Table.
        rs = statement.executeQuery("SELECT * " +
         "FROM Titles Where title_id = " + title_id);
      }
    }
    finally {

      // Release the connection
      pool.releaseConnection(con);
    }
    return rs;
  }

  // Method Name: buildClientArea()
  // Purpose: This method implements its parents abstract
  // method.  It represents the client area of the browser
  // window.
  public HTMLTable
    buildClientArea(HttpServletRequest request)
    throws Exception {

    // We are now getting ready to checkout.
    // get a reference to the HttpSession object
    HttpSession session = request.getSession(true);
    Vector basket = null;

    // Create the Table to return as the client area.
    HTMLTable table = new HTMLTable();
    table.setWidthByPixel(400);
    table.setAlignment(HTMLObject.CENTER);
    table.setCaption(new HTMLHeading("Shopping Basket Contents",
      HTMLHeading.H3));
    HTMLTableRow row = new HTMLTableRow();
    HTMLTableCell cell = new HTMLTableCell(HTMLTableCell.DATA);

    if ( session != null ) {

      // Get the Shopping Basket's current contents.
      basket = (Vector)session.getValue("basket");

      // Iterate over the basket's contents
      if ( basket != null ) {

        for ( int x = 0; x < basket.size(); x++ ) {

          row = new HTMLTableRow();

          Movie movie = (Movie)basket.elementAt(x);

          // Get the complete database representation of the
          // Movie based on title_id
          ResultSet rs = selectByTitleId(movie.getTitleId());

          if ( rs.next() ) {

            // Set the name attribute of the movie
            // to the result of the database query.
            movie.setName(rs.getString("title_name"));
          }

          // Add the name to the table cell for display
          cell = new HTMLTableCell(HTMLTableCell.DATA);
          cell.addObject(new HTMLText(movie.getName()));
          row.addObject(cell);

          // Add the price to the table cell for display
          cell =  new HTMLTableCell(HTMLTableCell.DATA);
          cell.addObject(new HTMLText(new Double(
            movie.getPrice()).toString()));
          row.addObject(cell);

          table.addObject(row);
        }

        // Add a row containing a link to empty the basket
        row = new HTMLTableRow();
        cell = new HTMLTableCell(HTMLTableCell.DATA);
        cell.addObject(
          new HTMLLink("/servlet/EmptyBasketServlet",
          new HTMLText("Empty Basket")));
        row.addObject(cell);

        // Add a row containing a link to complete the order
        cell = new HTMLTableCell(HTMLTableCell.DATA);
        cell.addObject(
          new HTMLLink("/servlet/ProcessOrderServlet",
          new HTMLText("Submit Order")));
        row.addObject(cell);

        table.addObject(row);
      }
      else {

        // If the basket was empty, say so.
        row = new HTMLTableRow();
        cell.addObject(new HTMLText("No items in basket!"));
        row.addObject(cell);
        table.addObject(row);
      }
    }
    return table;
  }

  //Get Servlet information
  public String getServletInfo() {

    return "ShoppingBasketServlet Information";
  }
}
