package com.ACME;

import java.util.*;
import java.sql.*;

// This bean implements the business logic of a shopping cart,
// including adding items, providing a table of items, and 
// communicating with the database.

public class CartBean {

  // Inner class to represent item/quantity pairs
  public static class CartItem {
    private String item;
    private int quantity;
    public CartItem(String name) {
      item = name;
      quantity = 1;
      }
    public void add() {quantity++;}
    public String getName() {return item;}
    public int getQuantity() {return quantity;}
    }

  private LinkedList cart;
  private String customerName;
  private String database;

  public CartBean() {
    cart = new LinkedList();
    }

  public void setDatabase(String d) {
    database = d;
    }

  public void setCustomer(String name) {
    customerName = name;
    }

  public String getCustomer() {
    return customerName;
    }

  // Add the item to the cart, after making sure it exists.

  public void setItem(String item) throws Exception {
    // Connect to the database to make sure item exists
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:" + database);
    String queryString =
        "SELECT Stock.Price " +
        "FROM Stock " +
        "WHERE Stock.Item = '" + item + "' ";
    Statement queryStatement = con.createStatement();
    ResultSet queryResult = queryStatement.executeQuery(queryString);

    // Check whether the result is empty. 
    if (queryResult.next()) {
      // Search for item in list
      int where = -1;
      for (int i = 0; i < cart.size(); i++) {
        if (((CartItem)cart.get(i)).getName().equals(item)) where = i;
        }
      // If not in list append new item to end
      if (where == -1) cart.addLast(new CartItem(item));
      // Otherwise, add 1 to quantity in cart
      else ((CartItem)cart.get(where)).add();
      }
    }

  // Empty the cart and put the order in the database.

  public void setCheckout(String s) throws Exception {
    if (s.equals("true") && !customerName.trim().equals("")) {

      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con = DriverManager.getConnection("jdbc:odbc:" + database);
      
      GregorianCalendar now = new GregorianCalendar();
      java.sql.Date date = new java.sql.Date(now.getTimeInMillis());
      String sqldate = date.toString();
      
      while (cart.size() > 0) {
        CartItem c = (CartItem)cart.removeFirst();
        String insertString = "INSERT INTO Purchases "
                        + "(Name, Item, Quantity, When) VALUES ('"
                        + customerName + "', '" + c.getName() + "', "
                        + c.getQuantity() + ", '" + sqldate + "')";

        Statement insertStatement = con.createStatement();
        insertStatement.executeUpdate(insertString);
        } 
      }
    }

  // Create a string of table rows giving items and quantities.
  // Note that this is not a particualry good idea, as it precludes
  // the JSP from setting its own output to some degree.

  public String getCart() {
    String reply = "";
    int items = cart.size();
    if (items == 0) return "<TR><TD>Cart Empty</TD></TR>";
    for (int i = 0; i < items; i++) {
      CartItem c = (CartItem)cart.get(i);
      reply += "<TR><TD>" + c.getName() + "</TD><TD>" + c.getQuantity() + "</TD></TR>";
      }
    return reply;
    }

  }

