import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;


// This servlet places orders from the modified form.

public class ACMEPurchase1 extends HttpServlet 
                          implements SingleThreadModel {

  // We will read the driver and database name from the web.xml file
  // in order to increase portability.
  private String driver;
  private String database;

  public void init(ServletConfig config) {
    driver = config.getInitParameter("Driver");
    database = config.getInitParameter("Database");
    }


  public void doPost(HttpServletRequest request,
                     HttpServletResponse response) 
              throws ServletException, IOException {

    Connection con;

    PrintWriter out = response.getWriter();


       // Get the current date in SQL form.

       GregorianCalendar now = new GregorianCalendar();
       java.sql.Date date = new java.sql.Date(now.getTimeInMillis());
       String sqldate = date.toString();

    try {
      // Register the driver (or the bridge) and make the 
      // connection based on web.xml file.
      if (driver.equals("MySQL")) {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/" + database);
        }
    else {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:" + database);
        }

      }

    // If there is a problem connecting, return an error message.
    catch(Exception ex) {
      out.println("<HTML><BODY><P>Error -- Database unreachable!</P></BODY></HTML>");
      return;
      }

    // Get the customer name and item purchased from the request
    String who = (request.getParameter("customerName")).trim();

    // If there was no name or item entered, notify the user. 
    if (who.equals("")) {
      out.println("<HTML><BODY><P>No customer name entered!</P></BODY></HTML>");
      return;
      }

   try {

    // We will start by getting all of the item names and prices from the Stock database
    // and dumping them to a LinkedList. 

    LinkedList itemNames = new LinkedList();
    LinkedList itemPrices = new LinkedList();

    String queryString =
        "SELECT Stock.Item, Stock.Price " +
        "FROM Stock";
    Statement queryStatement = con.createStatement();
    ResultSet queryResult = queryStatement.executeQuery(queryString);

    while (queryResult.next()) {
      String item = queryResult.getString("Item");
      itemNames.addLast(item); 
      String price = queryResult.getString("Price");
      itemPrices.addLast(price); 
      }

    queryResult.close();
    queryStatement.close();

    // This will in turn be used to get the parameters from the request.
    // Any parameter with a value > 0 will be used to add a new order.

    double total = 0;
    // We will keep the output as a running string until we know the order is ok.
    String responseString = "<HTML><BODY><P>Order placed for <B>" + who + "</B></BR>"; 

    for (int i = 0; i < itemNames.size(); i++) {
      String item = (String)itemNames.get(i);
      String quantityString = request.getParameter(item);

      // Make sure the parameter exists, and is a positive number.
      if (item == null) continue;
      int quantity = 0;
      try {quantity = Integer.parseInt(quantityString);}
      catch (NumberFormatException ex) {}

      if (quantity <= 0) continue;

      // Since this item was purchased, create and submit an input statement.

       // Insert the record using an SQL command.
       String insertString = "INSERT INTO Purchases "
                        + "(Name, Item, Quantity, When) VALUES ('"
                        + who + "', '" + item + "', "
                        + quantity + ", '" + sqldate + "')";
       //System.out.println(insertString);
       Statement insertStatement = con.createStatement();

       int count = insertStatement.executeUpdate(insertString);

       // When an update is done on a database, a record set is not
       // created. Instead, we can find out how many records were
       // affected. This returns 0 if the command affected no records.
       if (count < 1) {
         out.println("<HTML><BODY><P>Error handling request!</P></BODY></HTML>");
         return;
         }
       else {
         double price = Float.parseFloat((String)itemPrices.get(i));
         total = total + price * quantity;
         responseString += "" + quantity + " of " + item + " at $" + price + " each.<BR>";
         }

       insertStatement.close();
       }

    if (total > 0) {
      out.println(responseString);
      out.println("Total purchase: $" + total);
      out.println("</P></BODY></HTML>");
      }
   else {
      out.println("<HTML><BODY><P>No items ordered!</P></BODY></HTML>");
      }

    // Close everything
    con.close();

      }
    // If the SQL string is not in the correct form, this will result
    // (it must be handled). The user should never be able to cause this.
    catch(SQLException ex) {
      out.println("<HTML><BODY><P>Error handling request!</P></BODY></HTML>");
      return;
      }
    }

  }

