/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ee.ut.math.tvt2008.salessystem.ui.model;

import ee.ut.math.tvt2008.salessystem.domain.data.Sale;
import ee.ut.math.tvt2008.salessystem.domain.data.SoldItem;
import ee.ut.math.tvt2008.salessystem.domain.data.StockItem;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class CurrentPurchaseTableModel extends SaleInfoTableModel{
    
   public void addItem(SoldItem soldItem) {
        for(SoldItem item : sale.getSoldItems()){
            if(item.getStockItem().getId() == soldItem.getStockItem().getId()){
                item.setQuantity(item.getQuantity() + soldItem.getQuantity());
                return;
            }
        }
        sale.addSoldItem(soldItem);
        this.fireTableDataChanged();
    }

    public void addItem(StockItem stockItem) {
        for(SoldItem item : sale.getSoldItems()){
            if(item.getStockItem().getId() == stockItem.getId()){
                item.setQuantity(item.getQuantity() + stockItem.getQuantity());
                item.getStockItem().setQuantity(item.getQuantity());
                return;
            }
        }
        SoldItem soldItem = new SoldItem();
        soldItem.setName(stockItem.getName());
        soldItem.setPrice(stockItem.getPrice());
        soldItem.setStockItem(stockItem);
        soldItem.setQuantity(stockItem.getQuantity());
        sale.addSoldItem(soldItem);
        this.fireTableDataChanged();
    }

    public SoldItem getItemById(Long id) {
        for(SoldItem item : sale.getSoldItems()){
            if(item.getStockItem().getId() == id)return item;
        }
        return null;
    }


    public Object getValueAt(int rowIndex, int columnIndex) {
        SoldItem soldItem = (SoldItem) sale.getSoldItems().toArray()[rowIndex];
        switch(columnIndex){
            case 0: return soldItem.getId();
            case 1: return soldItem.getName();
            case 2: return soldItem.getQuantity();
            case 3: return soldItem.getPrice();
            case 4: return soldItem.getValue();
            default: return -1;
        }
    }
    
    public List<StockItem> getStockItems(){
        ArrayList<StockItem> stockItems = new ArrayList<StockItem>();
        for(SoldItem item : sale.getSoldItems()){
            stockItems.add(item.getStockItem());
        }
        return stockItems;
    }

    public void clear() {
        sale = null;
    }
}
