import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;


// This class demonstrates how you can insert records into a database.

public class ACMEPurchase 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 {

    int quantity;
    double price, total;

    Connection con;

    PrintWriter out = response.getWriter();

    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("customer")).trim();
    String what = (request.getParameter("item")).trim();
    String quantityString = (request.getParameter("quantity")).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;
      }
    if (what.equals("")) {
      out.println("<HTML><BODY><P>No item entered!</P></BODY></HTML>");
      return;
      }
    
    // Note that the quantity should be validated also!
    quantity = Integer.parseInt((request.getParameter("quantity")).trim());

   try {

    // Validate the item by checking the stock table, getting its price.
    String queryString =
        "SELECT Stock.Price " +
        "FROM Stock " +
        "WHERE Stock.Item = '" + what + "' ";
    Statement queryStatement = con.createStatement();
    ResultSet queryResult = queryStatement.executeQuery(queryString);

    // Check whether the result is empty
    if (queryResult.next()) {
      price = queryResult.getDouble("Price");
      }
    else {
      out.println("<HTML><BODY><P>No such item in stock.</P></BODY></HTML>");
      return;
      }


    // We will also get the current date, and convert it into an
    // SQL-fiendly format for Access.

    // This gets the current time, based on the gregorian calendar.
    GregorianCalendar now = new GregorianCalendar();


    // Create a date in standard YYYY-MM-DD
    // form generated from a java.sql.Date object.

    java.sql.Date date = new java.sql.Date(now.getTimeInMillis());
    String sqldate = date.toString();

    // Insert the record using an SQL command.
    String insertString = "INSERT INTO Purchases "
                        + "(Name, Item, Quantity, When) VALUES ('"
                        + who + "', '" + what + "', "
                        + 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>");
      }
    else {
      total = price * quantity;
      out.println("<HTML><BODY><P>");
      out.println("Order placed for <B>" + who + "</B></BR>");
      out.println("" + quantity + " of " + what + " at $" + price + " each.<BR>");
      out.println("Total purchase: $" + total);
      out.println("</P></BODY></HTML>");
      }

      // Close everything
      queryResult.close();
      queryStatement.close();
      insertStatement.close();
      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;
      }
    }

  }

