package cart;

import java.util.*;
import database.ProductDetails;

public class MyCart {
    Hashtable items = null;
    int numberOfItems = 0;

    public MyCart() {
        items = new Hashtable();
    }

    public void add(String productId, ProductDetails product) {
        if(items.containsKey(productId)) {
            ShoppingCartItem scitem = (ShoppingCartItem) items.get(productId);
            scitem.incrementQuantity();
        } else {
            ShoppingCartItem newItem = new ShoppingCartItem(product);
            items.put(productId, newItem);
        }

        numberOfItems++;
    }

    public void remove(String productId) {
        if(items.containsKey(productId)) {
            ShoppingCartItem scitem = (ShoppingCartItem) items.get(productId);
            scitem.decrementQuantity();

            if(scitem.getQuantity() <= 0)
                items.remove(productId);

            numberOfItems--;
        }
    }

    public Enumeration getItems() {
        return items.elements();
    }

    protected void finalize() throws Throwable {
        items.clear();
    }

    public int getNumberOfItems() {
        return numberOfItems;
    }

    public void clear() {
        items.clear();
        numberOfItems = 0;
    }
}

