/*
 *
 * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Sun Microsystems, Inc.
 * Use is subject to license terms.
 *
 */
package samples.jdbc.transactions;


import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.naming.*;

import javax.servlet.http.*;

import java.sql.*;

import javax.sql.*;


/**
 * This servlet is responsible for generating the pages which asks for a String input
 * It will generate a Greeting and save it in a database.
 */
public class WarehouseServlet extends HttpServlet {

    /**
      * The doGet method of the servlet. Handles all http GET request.
          * Required by the servlet specification.
          * @exception throws ServletException and IOException.
          */
    public void doGet(
            HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

        InitialContext initContext = null;
        Hashtable      env         = new java.util.Hashtable(1);
        Connection     con;
        String         dbName = "java:comp/env/jdbc/jdbc-transactions";

        try {
            initContext = new javax.naming.InitialContext();

            DataSource ds = (DataSource) initContext.lookup(dbName);

            con = ds.getConnection();

            ship(con, "123", "456", 8);

            String status = getStatus(con, "123", "456");

            con.close();
            response.setContentType("text/html");

            PrintWriter out = response.getWriter();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>" + status + "</title>");
            out.println("</head>");
            out.println("<body bgcolor=\"white\">");
            out.println("<h1>" + status + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } catch(Exception e) {
            System.out.println("- Exception creating InitialContext: "
                               + e.toString());
        }
    }

    /**
      * The doPost method of the servlet. Handles all http POST request.
          * Required by the servlet specification.
          * @exception throws ServletException and IOException.
          */
    public void doPost(
            HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        doGet(request, response);
    }

    /********************* Database Routines ***********************/
    private String selectStatus(
            Connection con, String productId, String orderId)
                throws SQLException {

        String result;
        String selectStatement = "select status "
                                 + "from order_item where product_id = ? "
                                 + "and order_id = ?";
        PreparedStatement prepStmt = con.prepareStatement(selectStatement);

        prepStmt.setString(1, productId);
        prepStmt.setString(2, orderId);

        ResultSet rs = prepStmt.executeQuery();

        if(rs.next()) {
            result = rs.getString(1);
        } else {
            result = "No rows found.";
        }

        prepStmt.close();

        return result;
    }

    private void updateOrderItem(
            Connection con, String productId, String orderId)
                throws SQLException {

        String updateStatement = "update order_item set status =  'shipped' "
                                 + "where product_id = ? "
                                 + "and order_id = ?";
        PreparedStatement prepStmt = con.prepareStatement(updateStatement);

        prepStmt.setString(1, productId);
        prepStmt.setString(2, orderId);
        prepStmt.executeUpdate();
        prepStmt.close();
    }

    private void updateInventory(
            Connection con, String productId, int quantity)
                throws SQLException {

        String updateStatement = "update inventory "
                                 + "set quantity = quantity - ? "
                                 + "where product_id = ?";
        PreparedStatement prepStmt = con.prepareStatement(updateStatement);

        prepStmt.setInt(1, quantity);
        prepStmt.setString(2, productId);
        prepStmt.executeUpdate();
        prepStmt.close();
    }

    /**
      * Updates the received for particular product inside the particular order.
          * sets the status to shipped
          * @param productID.
          * @param orderID
          * @param quantity the received quantity
          */
    public void ship(Connection con, String productId, String orderId,
                     int quantity) {

        try {
            con.setAutoCommit(false);
            updateOrderItem(con, productId, orderId);
            updateInventory(con, productId, quantity);
            con.commit();
        } catch(Exception ex) {
            try {
                con.rollback();
            } catch(SQLException sqx) {}
        }
    }

    /**
      * Sets the get the status for the particular product inside the particular order.
          * @param productID.
          * @param orderID
          * @return the status
          */
    public String getStatus(Connection con, String productId, String orderId)
            throws SQLException {
        return selectStatus(con, productId, orderId);
    }
}