/*
 * Copyright (c) 2004, 2005, ADAPT project partners (IST-2001-37126).
 * 
 * SubmitRetailerPurchaseOrderServlet.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.apache.axis.types.URI;
import org.eu.adapt.demonstrator.web.ADAPTLookAndFeel;
import org.eu.adapt.demonstrator.web.Navigation;
import org.eu.adapt.services.demo_1_1.RetailerService_wsdl.RetailerServiceLocator;
import org.eu.adapt.services.demo_1_1.retailer.CatalogBasicService_wsdl.CatalogBasicServiceLocator;
import org.eu.adapt.services.demo_1_1.retailer.CatalogBasicService_wsdl.CatalogBasicServicePortType;
import org.eu.adapt.services.demo_1_1.retailer.CatalogBasicService_wsdl.types.CatalogState;
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.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.Configuration_xsd.ConfigurationEndpointRole;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.Configuration_xsd.ConfigurationEndpointType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.Configuration_xsd.ConfigurationType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.RetailOrder_xsd.PartsOrderItem;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.RetailOrder_xsd.PartsOrderResponseType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.RetailOrder_xsd.PartsOrderType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.RetailOrder_xsd.CustomerDetailsType;
import org.ws_i.www.SampleApplications.SupplyChainManagement._2002_08.Retailer_wsdl.RetailerPortType;

public class SubmitRetailerPurchaseOrderServlet 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
            displayCalalogs(request, writer);

        Navigation.generateNavigationFooter(writer);
        ADAPTLookAndFeel.generatePageFooter(writer);
    }
        
    private void createPurchaseOrder(HttpServletRequest request, PrintWriter writer)
    {
        try
        {
//            String                          catalogBasicServiceURLString     = getInitParameter("CatalogBasicServiceURL");
//            String                          catalogItemBasicServiceURLString = getInitParameter("CatalogItemBasicServiceURL");
//            CatalogBasicServiceLocator      catalogBasicServiceLocator       = new CatalogBasicServiceLocator();
//            CatalogItemBasicServiceLocator  catalogItemBasicServiceLocator   = new CatalogItemBasicServiceLocator();
//            CatalogBasicServicePortType     catalogBasicServicePortType      = catalogBasicServiceLocator.getCatalog(new URL(catalogBasicServiceURLString));
//            CatalogItemBasicServicePortType catalogItemBasicServicePortType  = catalogItemBasicServiceLocator.getCatalogItem(new URL(catalogItemBasicServiceURLString));

            String retailerPurchaseOrderNumber = "RON" + _nextOrderNumber;
            _nextOrderNumber++;

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

            int         partsOrderItemsNumber = 0;
            Enumeration partsOrderItemNames   = request.getParameterNames();
            while (partsOrderItemNames.hasMoreElements())
            {
                String partsOrderItemName = (String) partsOrderItemNames.nextElement();

                if (! IS_ORDER_FLAG.equals(partsOrderItemName))
                {
                    try
                    {
                        int partsOrderItemQty = Integer.parseInt(request.getParameterValues(partsOrderItemName)[0]);
                        
                        if (partsOrderItemQty != 0)
                            partsOrderItemsNumber++;
                    }
                    catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException)
                    {
                    }
                    catch (NumberFormatException numberFormatException)
                    {
                    }
                }
            }
            PartsOrderItem[] partsOrderItems = new PartsOrderItem[partsOrderItemsNumber];

            int partsOrderItemIndex = 0;
            partsOrderItemNames     = request.getParameterNames();
            while (partsOrderItemNames.hasMoreElements())
            {
                String partsOrderItemName = (String) partsOrderItemNames.nextElement();

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

                        if (partsOrderItemQty != 0)
                        {
                            partsOrderItems[partsOrderItemIndex] = new PartsOrderItem();
                            partsOrderItems[partsOrderItemIndex].setProductNumber(partsOrderItemName);
                            partsOrderItems[partsOrderItemIndex].setPrice(100.0f);
                            partsOrderItems[partsOrderItemIndex].setQuantity(partsOrderItemQty);
                            partsOrderItemIndex++;
                        }
                    }
                    catch (NumberFormatException numberFormatException)
                    {
                    }
                }
            }
            PartsOrderType partsOrder = new PartsOrderType();
            partsOrder.setItem(partsOrderItems);
 
            CustomerDetailsType customerDetails = new CustomerDetailsType();
            customerDetails.setName("Name");
            customerDetails.setStreet1("Street 1");
            customerDetails.setStreet2("Street 2");
            customerDetails.setCity("City");
            customerDetails.setState("State");
            customerDetails.setZip("Zip");
            customerDetails.setCountry("Country");
            
            ConfigurationType           configuration             = new ConfigurationType();
            ConfigurationEndpointType[] configurationEndpoints    = new ConfigurationEndpointType[1];
            configurationEndpoints[0] = new ConfigurationEndpointType();
            configurationEndpoints[0].setRole(ConfigurationEndpointRole.Retailer);
            configurationEndpoints[0].setValue(new URI("test://test"));
            configuration.setUserId("Test");
            configuration.setServiceUrl(configurationEndpoints);

            int status = submitRetailerPurchaseOrder(partsOrder, customerDetails, configuration);

            ADAPTLookAndFeel.generateTableEntry("Retailer Purchase Order Number: " + retailerPurchaseOrderNumber, 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 submitRetailerPurchaseOrder(PartsOrderType partsOrder, CustomerDetailsType customerDetails, ConfigurationType configuration)
    {
        int status = RetailerPurchaseOrder.STATUS_UNKNOWN;
        
        try
        {
            String                 retailerServiceURLString = getInitParameter("RetailerServiceURL");
            RetailerServiceLocator retailerServiceLocator   = new RetailerServiceLocator();
            RetailerPortType       retailerServicePortType  = retailerServiceLocator.getRetailer(new URL(retailerServiceURLString));

            PartsOrderResponseType partsOrderResponse = retailerServicePortType.submitOrder(partsOrder, customerDetails, configuration);
            
            if ((partsOrderResponse.getItem() != null) && (partsOrderResponse.getItem().length != 0))
                status = RetailerPurchaseOrder.STATUS_ACKNOWLEDGED;
            else
                status = RetailerPurchaseOrder.STATUS_REJECTED;
        }
        catch (Exception exception)
        {
            System.err.println("Exception in \"submitRetailerPurchaseOrder\": " + exception);
            status = RetailerPurchaseOrder.STATUS_UNACKNOWLEDGED;
        }
        catch (Error error)
        {
            System.err.println("Error in \"submitRetailerPurchaseOrder\": " + error);
            status = RetailerPurchaseOrder.STATUS_UNACKNOWLEDGED;
        }
        
        return status;
    }

    private void displayCalalogs(HttpServletRequest request, PrintWriter writer)
    {
        try
        {
            String                          catalogBasicServiceURLString     = getInitParameter("CatalogBasicServiceURL");
            String                          catalogItemBasicServiceURLString = getInitParameter("CatalogItemBasicServiceURL");
            CatalogBasicServiceLocator      catalogBasicServiceLocator       = new CatalogBasicServiceLocator();
            CatalogItemBasicServiceLocator  catalogItemBasicServiceLocator   = new CatalogItemBasicServiceLocator();
            CatalogBasicServicePortType     catalogBasicServicePortType      = catalogBasicServiceLocator.getCatalog(new URL(catalogBasicServiceURLString));
            CatalogItemBasicServicePortType catalogItemBasicServicePortType  = catalogItemBasicServiceLocator.getCatalogItem(new URL(catalogItemBasicServiceURLString));

            String[] catalogNames = catalogBasicServicePortType.listCatalogs();

            writer.println("<FORM method=\"GET\" action=\"" + request.getRequestURI() + "\">");
            writer.println("<INPUT type=\"HIDDEN\" name=\"" + IS_ORDER_FLAG + "\" value=\"true\">");
            ADAPTLookAndFeel.generateTableHeader("Catalogs Event", null, writer);
            for (int catalogNameIndex = 0; (catalogNames != null) && (catalogNameIndex < catalogNames.length); catalogNameIndex++)
            {
                String       catalogName = catalogNames[catalogNameIndex];
                CatalogState state       = catalogBasicServicePortType.getCatalogState(catalogName);

                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 \"displayCalalogs\": " + exception);
            exception.printStackTrace(System.err);
        }
        catch (Error error)
        {
            System.err.println("Error in \"displayCalalogs\": " + error);
            error.printStackTrace(System.err);
        }
    }

    private int _nextOrderNumber = 1;
}