001package edu.pdx.cs410J.di;
002
003import javax.swing.table.AbstractTableModel;
004import java.text.NumberFormat;
005import java.text.ParseException;
006import java.util.ArrayList;
007import java.util.List;
008
009/**
010 * A swing table mode for the shopping cart
011 */
012public class CartTableModel extends AbstractTableModel
013{
014    private static final int TITLE_COLUMN = 0;
015    private static final int PRICE_COLUMN = 1;
016
017    private List<Book> books = new ArrayList<Book>();
018    private NumberFormat PRICE_FORMAT = NumberFormat.getCurrencyInstance();
019
020    public int getRowCount()
021    {
022        return books.size() + 1;
023    }
024
025    public int getColumnCount()
026    {
027        return 2;
028    }
029
030    public Object getValueAt( int row, int column )
031    {
032        if (isLastRow(row)) {
033            switch (column) {
034                case TITLE_COLUMN:
035                    return "Total";
036                case PRICE_COLUMN:
037                    double total = 0.0;
038                    for (Book book : books) {
039                        total += book.getPrice();
040                    }
041                    return PRICE_FORMAT.format( total );
042                default:
043                    throw new IllegalArgumentException( "Unknown column " + column );
044            }
045            
046        } else {
047            Book book = this.books.get(row);
048            switch (column) {
049                case TITLE_COLUMN:
050                    return book.getTitle();
051                case PRICE_COLUMN:
052                    return NumberFormat.getCurrencyInstance().format( book.getPrice() );
053                default:
054                    throw new IllegalArgumentException( "Unknown column " + column );
055            }
056        }
057    }
058
059    private boolean isLastRow( int row )
060    {
061        return row == getRowCount() - 1;
062    }
063
064    public void addBook( Book book )
065    {
066        int row = this.books.size();
067        this.books.add(book);
068        fireTableRowsInserted( row, row );
069    }
070
071    @Override
072    public String getColumnName( int index )
073    {
074        switch (index) {
075            case TITLE_COLUMN:
076                return "Title";
077            case PRICE_COLUMN:
078                return "Price";
079            default:
080                throw new IllegalArgumentException( "Unknown column: " + index );
081        }
082    }
083
084    /**
085     * Returns the total amount of the items in the cart
086     */
087    public double getTotal() {
088        String total = (String) getValueAt( getRowCount() - 1, PRICE_COLUMN );
089        try
090        {
091            return PRICE_FORMAT.parse( total ).doubleValue();
092        }
093        catch ( ParseException e )
094        {
095            throw new IllegalStateException( "Unparsable total: " + total );
096        }
097    }
098}