import javax.servlet.http.*;
import java.util.Vector;
import java.text.DecimalFormat;

import HTML.*;

/*
    This class serves a container for the Shopping Basket.
    It gets a reference to the Shopping Basket in the
    HttpSession and iterates over it compiling the totals
    for immediate display.  It is derived from HTMLTableCell.
*/

public class BasketCell extends HTMLTableCell {

  // Method Name: BasketCell() Constructor
  // Purpose : This is where all of the processing is done
  // in this class.  It takes the current list of movies in
  // the HttpSession object and displays them in a table.
  public BasketCell(HttpServletRequest request) {

    super(HTMLTableCell.DATA);

    int items = 0;
    double total = 0;

    // Get a reference to the current session
    HttpSession session = request.getSession(true);

    // Try to get the current basket in the shopping cart
    Vector basket = (Vector)session.getValue("basket");

    if ( basket != null ) {

      // Get the total number of items.
      items = basket.size();

      // Total the price of all the items.
      for ( int x = 0; x < items; x++ ) {

        total = total + ((Movie)basket.elementAt(x)).getPrice();
      }
    }
    setHorizontalAlign(CENTER);

    // Create a Table to display the results in.
    HTMLTable table = new HTMLTable();
    HTMLTableRow row = new HTMLTableRow();

    HTMLTableCell cell = new HTMLTableCell(HTMLTableCell.DATA);
    cell.setHorizontalAlign(CENTER);

    // Add an image link to the Shopping Basket
    HTMLLink link =
      new HTMLLink("/servlet/ShoppingBasketServlet",
      new HTMLImage("/images/shopping_cart.gif",
      "ShoppingCart"));

    // Shopping Basket Image Link
    cell.addObject(link);
    // Add the cell to the row
    row.addObject(cell);
    // Add the row to the table
    table.addObject(row);

    // Number of items
    row = new HTMLTableRow();
    cell = new HTMLTableCell(HTMLTableCell.DATA);
    HTMLText text = new HTMLText("Items: " + items);
    cell.addObject(text);
    row.addObject(cell);
    table.addObject(row);

    // Total Prices
    // Format the Price textual display
    DecimalFormat form = new DecimalFormat("##0.00");

    row = new HTMLTableRow();
    cell = new HTMLTableCell(HTMLTableCell.DATA);
    text = new HTMLText("Total: $" + form.format(total));
    cell.addObject(text);
    row.addObject(cell);

    table.addObject(row);

    addObject(table);
  }
}