001package edu.pdx.cs410J.di; 002 003import com.google.inject.Inject; 004 005import javax.swing.*; 006import javax.swing.event.TableModelEvent; 007import javax.swing.event.TableModelListener; 008import java.awt.*; 009import java.awt.event.ActionEvent; 010import java.awt.event.ActionListener; 011import java.util.logging.Logger; 012 013public class CheckoutPanel extends JPanel 014{ 015 private final CartTableModel cartTableModel; 016 017 private final Logger logger; 018 019 @Inject 020 public CheckoutPanel( BookInventory inventory, CreditCardService cardService, Logger logger ) { 021 setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) ); 022 this.logger = logger; 023 024 this.cartTableModel = new CartTableModel(); 025 026 final CheckoutInventoryTableModel inventoryModel = new CheckoutInventoryTableModel( inventory ); 027 inventoryModel.addTableModelListener( new TableModelListener() { 028 029 public void tableChanged( TableModelEvent event ) 030 { 031 if (inventoryModel.isLastColumn( event.getColumn() ) ) { 032 for (int i = event.getFirstRow(); i <= event.getLastRow(); i++) { 033 addToCart( inventoryModel.decrementInventry(event.getFirstRow()) ); 034 } 035 } 036 } 037 }); 038 this.add( new JScrollPane( new CheckoutInventoryTable( inventoryModel ) )); 039 this.add( Box.createVerticalStrut( 20 )); 040 this.add( new JScrollPane( new CartTable( cartTableModel ) )); 041 this.add( Box.createVerticalStrut( 20 )); 042 this.add( new PaymentPanel( cardService ) ); 043 044 this.add( Box.createVerticalGlue() ); 045 046 this.setPreferredSize( new Dimension( 600, 400) ); 047 } 048 049 private void addToCart(Book book) { 050 logger.fine("Adding " + book + " to cart"); 051 this.cartTableModel.addBook(book); 052 } 053 054 private class PaymentPanel extends JPanel 055 { 056 public PaymentPanel( final CreditCardService cardService ) { 057 setLayout( new BoxLayout( this, BoxLayout.X_AXIS ) ); 058 059 add(new JLabel( "Credit Card" )); 060 add( Box.createHorizontalStrut( 5 )); 061 final JTextField creditCard = new JTextField(30); 062 add(creditCard); 063 add( Box.createHorizontalStrut( 5 )); 064 JButton purchase = new JButton("Purchase"); 065 purchase.addActionListener( new ActionListener() { 066 067 public void actionPerformed( ActionEvent actionEvent ) 068 { 069 double total = cartTableModel.getTotal(); 070 String cardNumber = creditCard.getText(); 071 String confirmation = "Do you want to charge " + total + " to your " + cardNumber + " card?"; 072 String title = "Confirm charge"; 073 int confirm = 074 JOptionPane.showConfirmDialog( PaymentPanel.this, confirmation, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE ); 075 if (confirm == JOptionPane.YES_OPTION) { 076 CreditCard card = new CreditCard( cardNumber ); 077 cardService.debit( card, total ); 078 } 079 } 080 }); 081 add(Box.createHorizontalStrut( 5 )); 082 add(purchase); 083 } 084 } 085}