-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathProductStore.java
More file actions
83 lines (70 loc) · 2.74 KB
/
Copy pathProductStore.java
File metadata and controls
83 lines (70 loc) · 2.74 KB
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
82
83
package vendingmachine;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import vendingmachine.message.ExceptionMessage;
public class ProductStore {
private static final String PRODUCT_DELIMITER = ";";
private static final String PRODUCT_REGEX = "^\\[([^,]+),([0-9]+),([0-9]+)\\]$";
private static final Pattern PRODUCT_PATTERN = Pattern.compile(PRODUCT_REGEX);
private static final int NAME_INDEX = 1;
private static final int PRICE_INDEX = 2;
private static final int QUANTITY_INDEX = 3;
private final Map<Product, Integer> repository;
public ProductStore() {
repository = new HashMap<>();
}
public void initProductsByString(String input) {
Arrays.stream(input.split(PRODUCT_DELIMITER))
.forEach(this::handleProductByString);
}
private void handleProductByString(String value) {
Matcher matcher = PRODUCT_PATTERN.matcher(value);
if (matcher.find()) {
String name = matcher.group(NAME_INDEX);
int price = Integer.parseInt(matcher.group(PRICE_INDEX));
int quantity = Integer.parseInt(matcher.group(QUANTITY_INDEX));
Product product = new Product(name, price);
validateQuantity(quantity);
repository.put(product, quantity);
return;
}
throw new IllegalArgumentException(ExceptionMessage.INVALID_PRODUCT_NAME);
}
private void validateQuantity(int quantity) {
if (quantity <= 0) {
throw new IllegalArgumentException(ExceptionMessage.LACK_QUANTITY);
}
}
public boolean canBuySomething(int money) {
return getMinPrice() <= money && getLeftTotalProductCount() > 0;
}
private int getMinPrice() {
return repository.keySet()
.stream()
.mapToInt(Product::getPrice)
.min()
.orElseThrow(() -> new IllegalArgumentException(ExceptionMessage.INVALID_PRODUCT_NAME));
}
private int getLeftTotalProductCount() {
return repository.values()
.stream()
.mapToInt(Integer::intValue)
.sum();
}
public Product findProductByName(String name) {
return repository.keySet()
.stream()
.filter((product) -> product.getName().equals(name))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(ExceptionMessage.INVALID_PRODUCT_NAME));
}
public void purchaseProduct(Product product) {
repository.put(product, repository.get(product) - 1);
}
public int getLeftProductCount(Product product) {
return repository.get(product);
}
}