import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.*;

public class InventoryImpl extends UnicastRemoteObject
  implements Inventory {

  private Vector catalogItems = new Vector();

  public InventoryImpl() throws RemoteException {
  }

  public void addCatalogItem(CatalogItem inCatalogItem) 
    throws RemoteException {

    if(!catalogItems.contains(inCatalogItem)) {
      catalogItems.addElement(inCatalogItem);
      System.out.println("Added item: " + inCatalogItem);
    } else {
      System.out.println("Store already contains: " + inCatalogItem);
    }
  }

  public boolean inInventory(CatalogItem inCatalogItem)
    throws RemoteException {
    
    return catalogItems.contains(inCatalogItem);
  }

  public int getQuantityInInventory(CatalogItem inCatalogItem)
    throws RemoteException {

    CatalogItem item = null;
    int quantity = -1;
    if(catalogItems.contains(inCatalogItem)) {
      int index = catalogItems.indexOf(inCatalogItem);
      item = (CatalogItem)catalogItems.elementAt(index);
      quantity = item.checkQuantity();
      System.out.println("quantity="+quantity);
    }
    return quantity;
  }

  public Vector getCatalogItems() throws RemoteException {
    return catalogItems;
  }

  public static void main(String args[]) throws Exception {
    int port = 2001;

    if(System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    Registry reg = LocateRegistry.createRegistry(port);
    System.out.println("Creaded registry on port: " + port);

    InventoryImpl inventory = new InventoryImpl();

    inventory.addCatalogItem(new CD("Under the Table and Dreaming", 
      "Dave Matthews Band", 19, 2));
    inventory.addCatalogItem(new CD("Crash", 
      "Dave Matthews Band", 15, 3));
    inventory.addCatalogItem(new CD("Don't Know How to Party", 
      "The Mighty Mighty Boss Tones", 14.5, 1));

    reg.rebind("Inventory", inventory);
    System.out.println("Inventory created.");
  }
}
