// Fig. 16.16: ShoppingCart.java
// Shopping cart
package cartXML;
import javax.servlet.http.*;
import java.text.*;
import java.io.*;
import org.w3c.dom.*;
import java.util.*;

public class ShoppingCart implements HttpSessionBindingListener {
   private Vector books;
   private String username;
   private Database database;

   public ShoppingCart()
   { books = new Vector( 5 ); }

   public void valueBound( HttpSessionBindingEvent e ) {}

   public void valueUnbound( HttpSessionBindingEvent e )
   {
      if ( username == null )   // if username is null, exit
         return;

      save();
   }

   public void save()
   {
      database = new Database( "jdbc:odbc:cart", "anonymous",
         "guest" );
      database.connect();
      delete( username );

      for ( int i = 0; i < getLength(); i++ ) {
         Book b = ( Book ) books.elementAt( i );
         String productID = b.getProductID();
         int quantity = b.getQuantity();

         insert( username, productID, String.valueOf( quantity ) );
      }

      database.shutDown();
   }

   public void delete( String username )
   {
      String query = "DELETE * FROM Carts WHERE username = '"
         + username + "'";

      database.update( query );
   }

   public void insert( String username, String productID,
      String quantity )
   {
      Date today;
      String date;
      DateFormat dateFormatter;

      dateFormatter = DateFormat.getDateInstance(
         DateFormat.DEFAULT );
      today = new Date();
      date = dateFormatter.format(today);

      String query = "INSERT INTO Carts ( username, productID, "
         + "quantity, dateCreated ) VALUES ('" + username + "',"
         + productID + "," + quantity + ",'" +  date + "' )";

      database.update( query );
   }

   public void add( Book b )
   { books.addElement( b ); }

   public void remove( int i )
   { books.removeElementAt( i ); }

   public void setQuantity( int i, int quantity )
   {
      Book b = ( Book ) books.elementAt( i );

      b.setQuantity( quantity );
   }

   public String getUsername()
   { return username; }

   public void setUsername( String s )
   { username = s; }

   public String[] getDescription( int i )
   {
      Book b = ( Book ) books.elementAt( i );

      return b.getDescription();
   }

   public String getProductID( int i )
   {
     Book b = ( Book ) books.elementAt( i );

     return b.getProductID();
   }

   public int getQuantity( int i )
   {
      Book b = ( Book ) books.elementAt( i );

      return b.getQuantity();
   }

   public double getPrice( int i )
   {
      Book b = ( Book ) books.elementAt( i );

      return b.getPrice();
   }

   public String getFormattedPrice( int i )
   {
      Book b = ( Book ) books.elementAt( i );
      double price = b.getPrice();
      NumberFormat priceFormatter =
         NumberFormat.getCurrencyInstance();
      String formattedPrice = priceFormatter.format( price );

      return formattedPrice;
   }

   public int getLength()
   { return books.size(); }

   // returns the index of the vector if productID is found in
   //  cart, -1 otherwise
   public int contains( String id )
   {

      for ( int i = 0; i < getLength(); i++ ) {
         Book b = ( Book ) books.elementAt( i );
            String bookID = b.getProductID();

            if ( bookID != null && bookID.equals( id ) )
               return i;
      }

      return -1;
   }

   public String getTotal()
   {
      double total = 0;

      for ( int i = 0; i < getLength(); i++ )
         total += getPrice( i ) * getQuantity( i );

      NumberFormat priceFormatter =
         NumberFormat.getCurrencyInstance();
      String formattedTotal = priceFormatter.format( total );

      return formattedTotal;
   }

   public Document viewCartXML()
   {
      XMLCreator xmlCreator = new XMLCreator();
      Node cartNode = xmlCreator.initialize( "cart" );

      xmlCreator.addAttribute( cartNode, "numItems",
         String.valueOf( getLength() ) );
      xmlCreator.addAttribute( cartNode, "total", getTotal() );

      if ( getLength() != 0 ) {

         for ( int i = 0; i < getLength(); i++ ) {
            Node itemNode = xmlCreator.addChild( cartNode,
               "item" );

            xmlCreator.addTextNode( xmlCreator.addChild(
               itemNode, "productID" ), getProductID( i ) );
            xmlCreator.addTextNode( xmlCreator.addChild(
               itemNode, "quantity" ),
               String.valueOf( getQuantity( i ) ) );
            xmlCreator.addTextNode( xmlCreator.addChild(
               itemNode, "price" ), getFormattedPrice( i ) );

            String description[] = getDescription( i );

            xmlCreator.addTextNode( xmlCreator.addChild(
               itemNode, "title" ), description[ 0 ] );
            xmlCreator.addTextNode( xmlCreator.addChild(
               itemNode, "author" ), description[ 1 ] );
            xmlCreator.addTextNode( xmlCreator.addChild(
               itemNode, "isbn" ), description[ 2 ] );
         }

      }

      return xmlCreator.getDocument();
   }
}

/*
 **************************************************************************
 * (C) Copyright 2001 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 **************************************************************************
*/
