<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="org.jboss.bpel.samples.ordermanagement.OrderManager" %>
<%@ page import="java.util.Map" %>
<%@ page import="org.jboss.bpel.samples.ordermanagement.CustomerOrder" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.Date" %>
<%
    InitialContext ctx;
    OrderManager orderManager;
    Map orders;
    String approveOrderNum = request.getParameter("approve");

    try {
        ctx = new InitialContext();
    } catch (NamingException e) {
        throw new RuntimeException("Unable to create JNDI context.", e);
    }
    try {
        orderManager = (OrderManager) ctx.lookup("OrderManagerBean/remote");
    } catch (NamingException e) {
        throw new RuntimeException("Unable to lookup OrderManager Service Bean.", e);
    }

    if (approveOrderNum != null && !approveOrderNum.trim().equals("")) {
        orderManager.approveOrder(approveOrderNum);
    }
    orders = orderManager.getOrders();
%>
<html>
    <head>
        <title>Order Manager Service - Order Approval</title>
        <link rel='stylesheet' href='./style.css'>
        <meta http-equiv="refresh" content="3;url=index.jsp">
    </head>
    <html>
        <h1>Order Manager - Orders For Approval</h1>

        <table id="data-table" border="1">
            <colgroup>
                <col width="25%"/><col width="25%"/><col width="20%"/><col width="20%"/><col width="10%"/>
            </colgroup>
            <tr id="table-head">
                <td>Order Date</td><td>Order Number</td><td>Customer Number</td><td>Customer Name</td><td>&nbsp;</td>
            </tr>
            <%
                Iterator orderSet = orders.entrySet().iterator();
                while (orderSet.hasNext()) {
                    Map.Entry orderEntry = (Map.Entry) orderSet.next();
                    String orderNum = (String) orderEntry.getKey();
                    CustomerOrder order = (CustomerOrder) orderEntry.getValue();
                    Date time = order.getHeader().getOrderDate().getTime();
                    String customerNumber = order.getHeader().getCustomerNumber();
                    String company = order.getHeader().getBillTo().getCompany();
            %>
            <tr id="table-row">
                <td><%=time%></td><td><%=orderNum%></td><td><%=customerNumber%></td><td><%=company%></td><td><a href="index.jsp?approve=<%=orderNum%>">Approve</a></td>
            </tr>
                    <%
                }
            %>
            <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        </table>
        
    </html>
</html>
