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

package org.eu.adapt.demonstrator.web.demo;

import java.io.*;
import java.net.URL;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;
import org.eu.adapt.demonstrator.web.ADAPTLookAndFeel;
import org.eu.adapt.demonstrator.web.Navigation;
import org.eu.adapt.services.demo_1_1.ManufacturerService_wsdl.ManufacturerServiceLocator;
import org.eu.adapt.services.demo_1_1.retailer.CatalogItemBasicService_wsdl.CatalogItemBasicServiceLocator;
import org.eu.adapt.services.demo_1_1.retailer.CatalogItemBasicService_wsdl.CatalogItemBasicServicePortType;
import org.eu.adapt.services.demo_1_1.retailer.CatalogItemBasicService_wsdl.types.CatalogItemState;
import org.eu.adapt.services.demo_1_1.retailer.ProductBasicService_wsdl.ProductBasicServiceLocator;
import org.eu.adapt.services.demo_1_1.retailer.ProductBasicService_wsdl.ProductBasicServicePortType;
import org.eu.adapt.services.demo_1_1.retailer.ProductBasicService_wsdl.types.ProductState;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.Configuration_xsd.ConfigurationType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_10.Manufacturer.CallBack.StartHeaderType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_10.ManufacturerPO_xsd.Item;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_10.ManufacturerPO_xsd.ItemList;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_10.ManufacturerPO_xsd.PurchOrdType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_10.Manufacturer_wsdl.ManufacturerPortType;

public class SubmitManufacturerPurchaseOrderServlet extends HttpServlet
{
    private static final String IS_ORDER_FLAG = "IsOrderFlag";
    
    public void init()
        throws ServletException
    {
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
    {
        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");

        PrintWriter writer = response.getWriter();

        ADAPTLookAndFeel.generatePageHeader("..", writer);
        Navigation.generateNavigationHeader("..", writer);

        boolean isOrder = request.getParameter(IS_ORDER_FLAG) != null;
        if (isOrder)
            createPurchaseOrder(request, writer);
        else
            displayProducts(request, writer);

        Navigation.generateNavigationFooter(writer);
        ADAPTLookAndFeel.generatePageFooter(writer);
    }

    private void createPurchaseOrder(HttpServletRequest request, PrintWriter writer)
    {
        try
        {
//            String                          productBasicServiceURLString     = getInitParameter("ProductBasicServiceURL");
//            String                          catalogItemBasicServiceURLString = getInitParameter("CatalogItemBasicServiceURL");
//            ProductBasicServiceLocator      productBasicServiceLocator       = new ProductBasicServiceLocator();
//            CatalogItemBasicServiceLocator  catalogItemBasicServiceLocator   = new CatalogItemBasicServiceLocator();
//            ProductBasicServicePortType     productBasicServicePortType      = productBasicServiceLocator.getProduct(new URL(productBasicServiceURLString));
//            CatalogItemBasicServicePortType catalogItemBasicServicePortType  = catalogItemBasicServiceLocator.getCatalogItem(new URL(catalogItemBasicServiceURLString));

            String manufacturerPurchaseOrderNumber = "MON" + _nextOrderNumber;
            _nextOrderNumber++;

            ADAPTLookAndFeel.generateTableHeader("Retailer Order Event: " + manufacturerPurchaseOrderNumber, null, writer);

            PurchOrdType purchOrdType = new PurchOrdType();
            purchOrdType.setCustomerRef(ManufacturerItemsDefs.CUSTOMER_0);
            purchOrdType.setOrderNum(manufacturerPurchaseOrderNumber);
            int         itemsNumber = 0;
            Enumeration itemNames   = request.getParameterNames();
            while (itemNames.hasMoreElements())
            {
                String itemName = (String) itemNames.nextElement();

                if (! IS_ORDER_FLAG.equals(itemName))
                {
                    try
                    {
                        int itemQty = Integer.parseInt(request.getParameterValues(itemName)[0]);
                        
                        if (itemQty != 0)
                            itemsNumber++;
                    }
                    catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException)
                    {
                    }
                    catch (NumberFormatException numberFormatException)
                    {
                    }
                }
            }
            Item[] items = new Item[itemsNumber];

            int itemIndex = 0;
            itemNames     = request.getParameterNames();
            while (itemNames.hasMoreElements())
            {
                String itemName = (String) itemNames.nextElement();

                if (! IS_ORDER_FLAG.equals(itemName))
                {
                    try
                    {
                        int itemQty = Integer.parseInt(request.getParameterValues(itemName)[0]);

                        if (itemQty != 0)
                        {
                            items[itemIndex] = new Item();
                            items[itemIndex].setID(itemName);
                            items[itemIndex].setQty(itemQty);
                            items[itemIndex].setPrice(25.0f);
                            itemIndex++;
                        }
                    }
                    catch (NumberFormatException numberFormatException)
                    {
                    }
                }
            }

            ItemList itemList = new ItemList();
            itemList.setItem(items);
            purchOrdType.setItems(itemList);
            purchOrdType.setTotal(100.0f);
            ConfigurationType configuration = new ConfigurationType();
            StartHeaderType startHeader = new StartHeaderType();

            int status = submitManufacturerPurchaseOrder(purchOrdType, configuration, startHeader);

            ADAPTLookAndFeel.generateTableEntry("Manufacturer Purchase Order Number: " + manufacturerPurchaseOrderNumber, null, "Status: " + ManufacturerPurchaseOrder.statusToString(status), null, writer);
 
            ADAPTLookAndFeel.generateTableFooter(writer);
        }
        catch (Exception exception)
        {
            System.err.println("Exception in \"createPurchaseOrder\": " + exception);
            exception.printStackTrace(System.err);
        }
        catch (Error error)
        {
            System.err.println("Error in \"createPurchaseOrder\": " + error);
            error.printStackTrace(System.err);
        }
    }

    private int submitManufacturerPurchaseOrder(PurchOrdType purchOrd, ConfigurationType configuration, StartHeaderType startHeader)
    {
        int status = ManufacturerPurchaseOrder.STATUS_UNKNOWN;
        
        try
        {
            String                     manufacturerOrderServiceURLString = getInitParameter("ManufacturerOrderServiceURL");
            ManufacturerServiceLocator manufacturerServiceLocator        = new ManufacturerServiceLocator();
            ManufacturerPortType       manufacturerOrderServicePortType  = manufacturerServiceLocator.getOrder(new URL(manufacturerOrderServiceURLString));

            if (manufacturerOrderServicePortType.submitPO(purchOrd, configuration, startHeader))
                status = ManufacturerPurchaseOrder.STATUS_ACKNOWLEDGED;
            else
                status = ManufacturerPurchaseOrder.STATUS_REJECTED;
        }
        catch (Exception exception)
        {
            System.err.println("Exception in \"submitManufacturerPurchaseOrder\": " + exception);
            status = ManufacturerPurchaseOrder.STATUS_UNACKNOWLEDGED;
        }
        catch (Error error)
        {
            System.err.println("Error in \"submitManufacturerPurchaseOrder\": " + error);
            status = ManufacturerPurchaseOrder.STATUS_UNACKNOWLEDGED;
        }
        
        return status;
    }

    private void displayProducts(HttpServletRequest request, PrintWriter writer)
    {
        try
        {
            String                          productBasicServiceURLString     = getInitParameter("ProductBasicServiceURL");
            String                          catalogItemBasicServiceURLString = getInitParameter("CatalogItemBasicServiceURL");
            ProductBasicServiceLocator      productBasicServiceLocator       = new ProductBasicServiceLocator();
            CatalogItemBasicServiceLocator  catalogItemBasicServiceLocator   = new CatalogItemBasicServiceLocator();
            ProductBasicServicePortType     productBasicServicePortType      = productBasicServiceLocator.getProduct(new URL(productBasicServiceURLString));
            CatalogItemBasicServicePortType catalogItemBasicServicePortType  = catalogItemBasicServiceLocator.getCatalogItem(new URL(catalogItemBasicServiceURLString));

            String[] productNames = productBasicServicePortType.listProducts();

            writer.println("<FORM method=\"GET\" action=\"" + request.getRequestURI() + "\">");
            writer.println("<INPUT type=\"HIDDEN\" name=\"" + IS_ORDER_FLAG + "\" value=\"true\">");
            ADAPTLookAndFeel.generateTableHeader("Retailer Order Event", null, writer);
            for (int productNameIndex = 0; (productNames != null) && (productNameIndex < productNames.length); productNameIndex++)
            {
                String       productName = productNames[productNameIndex];
                ProductState state       = productBasicServicePortType.getProductState(productName);

                String[] catalogItemNames = state.getCatalogItemNames();
                for (int catalogItemIndex = 0; (catalogItemNames != null) && (catalogItemIndex < catalogItemNames.length); catalogItemIndex++)
                {
                    String           catalogItemName  = catalogItemNames[catalogItemIndex];
                    CatalogItemState catalogItemState = catalogItemBasicServicePortType.getCatalogItemState(catalogItemName);

                    String formText = "<INPUT type=\"text\" name=\"" + catalogItemState.getName() + "\" value=\"0\">";

                    ADAPTLookAndFeel.generateTableEntry(catalogItemState.getName() + ", " + catalogItemState.getDescription(), null, formText, null, writer);
                }
            }
            ADAPTLookAndFeel.generateTableEntry("<INPUT type=\"SUBMIT\" value=\"Submit\">", null, writer);
            ADAPTLookAndFeel.generateTableFooter(writer);
            writer.println("</FORM>");
        }
        catch (Exception exception)
        {
            System.err.println("Exception in \"displayProducts\": " + exception);
            exception.printStackTrace(System.err);
        }
        catch (Error error)
        {
            System.err.println("Error in \"displayProducts\": " + error);
            error.printStackTrace(System.err);
        }
    }

    private int _nextOrderNumber = 1;
}