-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCart.java
85 lines (65 loc) · 2.31 KB
/
Cart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package C212Amazon;
import java.util.HashMap;
import java.util.Set;
import java.util.Date;
/**
* Cart
* Cart represents a buyers cart
*/
public class Cart {
private int buyerID;
private HashMap<Item, Integer> cart = new HashMap<>(); // Shopping cart.
private PurchaseHistoryDataWriter purchaseHistoryDataWriter = new PurchaseHistoryDataWriter();
private PurchaseHistoryDataReader purchaseHistoryDataReader = new PurchaseHistoryDataReader();
private DataReader dataReader = new DataReader();
private DataWriter dataWriter = new DataWriter();
public Cart (int buyerID){
this.buyerID = buyerID;
}
/**
* adds a product to the cart
* @param item An Item object
*/
public void addToCart(Item item) {
if(cart.get(item) == null) {
System.out.println(item);
cart.put(item, 1);
}
else {
System.out.println(item);
cart.put(item, cart.get(item) + 1);
}
}
public boolean checkout() {
// 1. get unique cartID
// call the reader to get the latest value and + 1
int cartID = purchaseHistoryDataReader.getCartId();
Set<Item> keys = cart.keySet();
if(keys.size() == 0) {
return false;
}
else {
// 2. iterate over every item in cart
for (Item item : keys) {
// 3. get item parameters
int qty = cart.get(item) == null ? 0 : cart.get(item);
int productID = item.getProductID();
cart.remove(item);
// 4. write cart to purchaseHistory database
purchaseHistoryDataWriter.createPurchaseHistory(cartID, buyerID, productID, qty);
String testCurrentQuantity = "" + (dataReader.getDb("inventory", "quantity", productID));
int currentQuantity = testCurrentQuantity.equals("")? 0 : Integer.parseInt(testCurrentQuantity);
int newQuantity = (currentQuantity - qty) < 0 ? 0 : currentQuantity - qty;
dataWriter.setDb("inventory", "quantity", productID, newQuantity);
}
return true;
}
}
/**
* Method to get the cart
* @return This cart
*/
public HashMap<Item, Integer> getCart() {
return cart;
}
}