/*
 * Copyright (c) 2004, 2005, ADAPT project partners (IST-2001-37126).
 *
 * ProductBasicServiceBean.java
 */

package org.eu.adapt.demonstrator.bs.retailer;

import java.util.Collection;
import java.util.Iterator;
import java.rmi.RemoteException;
import javax.ejb.FinderException;
import javax.ejb.SessionContext;
import javax.ejb.SessionBean;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.eu.adapt.demonstrator.eb.retailer.ProductHomeLocal;
import org.eu.adapt.demonstrator.eb.retailer.ProductLocal;
import org.eu.adapt.demonstrator.eb.retailer.ManufacturerLocal;
import org.eu.adapt.demonstrator.eb.retailer.CatalogItemLocal;
import org.eu.adapt.demonstrator.eb.retailer.PurchaseOrderItemLocal;
import org.eu.adapt.demonstrator.eb.retailer.WarehouseLocal;
import org.eu.adapt.demonstrator.eb.retailer.InventoryLocal;
import org.eu.adapt.services.demo_1_1.retailer.ProductBasicService_wsdl.types.ProductState;
import org.eu.adapt.services.demo_1_1.retailer.ProductBasicService_wsdl.ProductBasicServicePortType;

public class ProductBasicServiceBean implements SessionBean, ProductBasicServicePortType
{
    public String[] listProducts()
       throws RemoteException
    {
        String[] productNames = null;

        try
        {
            Collection products         = _productHome.findAll();
            Iterator   productsIterator = products.iterator();

            productNames = new String[products.size()];
            int index = 0;
            while (productsIterator.hasNext())
            {
                productNames[index] = ((ProductLocal) productsIterator.next()).getName();
                index++;
            }
        }
        catch (FinderException findException)
        {
            productNames = new String[0];
            System.out.println("Unable to find all products: \"" + findException + "\"");
        }
        catch (Exception exception)
        {
            productNames = new String[0];
            System.out.println("Exception: \"" + exception + "\"");
        }
        catch (Error error)
        {
            productNames = new String[0];
            System.out.println("Error: \"" + error + "\"");
        }

        return productNames;
    }

    public ProductState getProductState(String productName)
        throws RemoteException
    {
        ProductState state = new ProductState();

        try
        {
            ProductLocal product = _productHome.findByPrimaryKey(productName);

            state.setName(product.getName());

            int index = 0;

            Collection manufacturers         = product.getManufacturers();
            Iterator   manufacturersIterator = manufacturers.iterator();
            String[]   manufacturerNames     = new String[manufacturers.size()];
            index = 0;
            while (manufacturersIterator.hasNext())
            {
                manufacturerNames[index] = ((ManufacturerLocal) manufacturersIterator.next()).getName();
                index++;
            }
            state.setManufacturerNames(manufacturerNames);

            Collection catalogItems         = product.getCatalogItems();
            Iterator   catalogItemsIterator = catalogItems.iterator();
            String[]   catalogItemNames     = new String[catalogItems.size()];
            index = 0;
            while (catalogItemsIterator.hasNext())
            {
                catalogItemNames[index] = ((CatalogItemLocal) catalogItemsIterator.next()).getId();
                index++;
            }
            state.setCatalogItemNames(catalogItemNames);

            Collection purchaseOrderItems         = product.getPurchaseOrderItems();
            Iterator   purchaseOrderItemsIterator = purchaseOrderItems.iterator();
            String[]   purchaseOrderItemNumbers   = new String[purchaseOrderItems.size()];
            index = 0;
            while (purchaseOrderItemsIterator.hasNext())
            {
                purchaseOrderItemNumbers[index] = ((PurchaseOrderItemLocal) purchaseOrderItemsIterator.next()).getNumber();
                index++;
            }
            state.setPurchaseOrderItemNumbers(purchaseOrderItemNumbers);

            Collection warehouses         = product.getWarehouses();
            Iterator   warehousesIterator = warehouses.iterator();
            String[]   warehouseNames     = new String[warehouses.size()];
            index = 0;
            while (warehousesIterator.hasNext())
            {
                warehouseNames[index] = ((WarehouseLocal) warehousesIterator.next()).getName();
                index++;
            }
            state.setWarehouseNames(warehouseNames);

            Collection inventories         = product.getInventories();
            Iterator   inventoriesIterator = inventories.iterator();
            String[]   inventoryNumbers    = new String[inventories.size()];
            index = 0;
            while (inventoriesIterator.hasNext())
            {
                inventoryNumbers[index] = ((InventoryLocal) inventoriesIterator.next()).getNumber();
                index++;
            }
            state.setInventoryNumbers(inventoryNumbers);
        }
        catch (FinderException finderException)
        {
            System.out.println("Unable to find product: \"" + productName + "\"");
        }
        catch (Exception exception)
        {
            System.out.println("ProductBasicServiceBean.getProductState exception: \"" + exception + "\"");
            throw new RemoteException("ProductBasicServiceBean.getProductState exception", exception);
        }
        catch (Error error)
        {
            System.out.println("ProductBasicServiceBean.getProductState error: \"" + error + "\"");
            throw new RemoteException("ProductBasicServiceBean.getProductState error", error);
        }

        return state;
    }

    public void addStock(String productName, int amount)
        throws RemoteException
    {
        try
        {
            ProductLocal   product     = _productHome.findByPrimaryKey(productName);
            Collection     inventories = product.getInventories();
            InventoryLocal inventory   = (InventoryLocal) inventories.iterator().next();
            
            inventory.setAmount(inventory.getAmount() + amount);
        }
        catch (FinderException finderException)
        {
            System.out.println("Unable to find product: \"" + productName + "\"");
        }
        catch (Exception exception)
        {
            System.out.println("ProductBasicServiceBean.addStock exception: \"" + exception + "\"");
            throw new RemoteException("ProductBasicServiceBean.addStock exception", exception);
        }
        catch (Error error)
        {
            System.out.println("ProductBasicServiceBean.addStock error: \"" + error + "\"");
            throw new RemoteException("ProductBasicServiceBean.addStock error", error);
        }
    }

    public void removeStock(String productName, int amount)
        throws RemoteException
    {
        try
        {
            ProductLocal   product     = _productHome.findByPrimaryKey(productName);
            Collection     inventories = product.getInventories();
            InventoryLocal inventory   = (InventoryLocal) inventories.iterator().next();
            
            inventory.setAmount(inventory.getAmount() - amount);
        }
        catch (FinderException finderException)
        {
            System.out.println("Unable to find product: \"" + productName + "\"");
        }
        catch (Exception exception)
        {
            System.out.println("ProductBasicServiceBean.removeStock exception: \"" + exception + "\"");
            throw new RemoteException("ProductBasicServiceBean.removeStock exception", exception);
        }
        catch (Error error)
        {
            System.out.println("ProductBasicServiceBean.removeStock error: \"" + error + "\"");
            throw new RemoteException("ProductBasicServiceBean.removeStock error", error);
        }
    }

    public void setSessionContext(SessionContext sessionContext)
    {
        _sessionContext = sessionContext;
    }

    public void unsetSessionContext()
    {
        _sessionContext = null;
    }

    public void ejbCreate()
    {
        try
        {
            InitialContext initialContext = new InitialContext();

//            _productHome = (ProductHomeLocal) initialContext.lookup("java:comp/env/ejb/ProductHomeLocal");
            _productHome = (ProductHomeLocal) initialContext.lookup("local/Retailer_ProductEB");

            initialContext.close();
        }
        catch (NamingException namingException)
        {
            System.out.println("Name lookup problem: \"" + namingException + "\"");
            namingException.printStackTrace(System.out);
        }
        catch (Exception exception)
        {
            System.out.println("Problem: \"" + exception + "\"");
            exception.printStackTrace(System.out);
        }
        catch (Error error)
        {
            System.out.println("Problem: \"" + error + "\"");
            error.printStackTrace(System.out);
        }
    }

    public void ejbActivate()
    {
    }

    public void ejbPassivate()
    {
    }

    public void ejbLoad()
    {
    }

    public void ejbStore()
    {
    }    

    public void ejbRemove()
    {
        _productHome = null;
    }

    private SessionContext _sessionContext = null;
    
    private transient ProductHomeLocal _productHome = null;
}