001package edu.pdx.cs410J.di;
002
003import javax.swing.table.AbstractTableModel;
004import java.text.NumberFormat;
005import java.util.Iterator;
006import java.util.Set;
007
008/**
009 * A swing table model that lists the contents of a {@link BookInventory}
010 */
011public class BookInventoryTableModel extends AbstractTableModel
012{
013    private static final int AUTHOR_COLUMN = 0;
014    private static final int TITLE_COLUMN = 1;
015    private static final int PRICE_COLUMN = 2;
016    private static final int QUANTITY_COLUMN = 3;
017
018
019    protected final BookInventory inventory;
020
021    public BookInventoryTableModel( BookInventory inventory )
022    {
023        this.inventory = inventory;
024    }
025
026    public int getRowCount()
027    {
028        return inventory.getBooks().size();
029    }
030
031    public int getColumnCount()
032    {
033        return 4;
034    }
035
036    @Override
037    public String getColumnName( int column )
038    {
039        switch(column) {
040            case AUTHOR_COLUMN:
041                return "Author";
042            case TITLE_COLUMN:
043                return "Title";
044            case PRICE_COLUMN:
045                return "Price";
046            case QUANTITY_COLUMN:
047                return "Quantity";
048            default:
049                throw new IllegalArgumentException( "Unknown column: " + column );
050        }
051    }
052
053    public Object getValueAt( int row, int column )
054    {
055        Book book = getBook( row );
056
057        switch(column) {
058            case AUTHOR_COLUMN:
059                return book.getAuthor();
060            case TITLE_COLUMN:
061                return book.getTitle();
062            case PRICE_COLUMN:
063                return NumberFormat.getCurrencyInstance().format( book.getPrice() );
064            case QUANTITY_COLUMN:
065                return inventory.getCopies( book );
066            default:
067                throw new IllegalArgumentException( "Unknown column: " + column );
068        }
069    }
070
071    public Book getBook( int i )
072    {
073        Set<Book> books = inventory.getBooks();
074        assert i < books.size();
075        Iterator<Book> iter = books.iterator();
076        for (int j = 0; j < i; j++) {
077            iter.next();
078        }
079        return iter.next();
080    }
081
082    public Book decrementInventry( int row )
083    {
084        Book book = getBook( row );
085        inventory.remove( book );
086        fireTableCellUpdated( row, QUANTITY_COLUMN );
087        return book;
088    }
089}