package JThread.examples.shopper;

import java.util.*;
import java.io.*;

public class ItemStock implements Serializable {
    private Hashtable _items;
    
    public ItemStock() {
        _items = new Hashtable();
    }
    
    public void initStock() {
        _items.put("MegaHits", new Integer(30));
        _items.put("Killer Rabbits", new Integer(30));
        _items.put("Jaws XXIII", new Integer(30));
        _items.put("Six Sense", new Integer(30));
        _items.put("Aliens", new Integer(30));
        _items.put("Snow White", new Integer(30));
    }
    
    public void stock(String new_item, int num) {
        Integer in = (Integer)_items.get(new_item);
        if (in == null) {
            _items.put(new_item, new Integer(num));
        } else {
            _items.put(new_item, new Integer(num + in.intValue()));
        }
    }
    
    public void stock(ItemStock s) {
        Enumeration keys = s._items.keys();
        Enumeration elements = s._items.elements();
        while(keys.hasMoreElements()) {
            _items.put((String)keys.nextElement(), (Integer)elements.nextElement());
        }
    }
            
    public void buy(String item, int num) {
        Integer in = (Integer)_items.get(item);
        if (in == null) {
            System.out.println(item + " is currently out of stock.");
        } else {
            int in_stock = in.intValue();
            if (in_stock < num) {
                System.out.println("Warning: items in stock is not enough, buying what even the store has: " + in_stock);
                _items.remove(item);
            } else if (in_stock == num) {
                _items.remove(item);
            } else {
                _items.put(item, new Integer(in_stock - num));
            }
        }
    }
    
    public String toString() {
        return _items.toString();
    }
}