package org.hso.ecommerce.entities.shop; import java.util.ArrayList; import java.util.List; // Not a db entity. Just for session storage public class ShoppingCart { private final static int MAX_ITEMS = 10; private int revision; private ArrayList items; public ShoppingCart() { clear(); } public void clear() { items = new ArrayList<>(); revision = (int) Math.round(Math.random() * 0xFFFF); } public List getItems() { return items; } public int getItemCount() { int count = 0; for (ShoppingCartItem i : items) { count += i.getAmount(); } return count; } public int getRevision() { return revision; } public void addArticle(Article article, int quantity) { this.revision++; for (ShoppingCartItem i : items) { if (i.getArticleId() == article.id) { i.addAmount(quantity); return; } } items.add(new ShoppingCartItem(quantity, article)); } public void setArticleCount(Article article, Integer quantity) { this.revision++; boolean found = false; for (ShoppingCartItem i : items) { if (i.getArticleId() == article.id) { i.setAmount(quantity); found = true; break; } } if (!found) { items.add(new ShoppingCartItem(quantity, article)); } items.removeIf(i -> i.getAmount() <= 0); } public int getArticleCount(Article article) { for (ShoppingCartItem i : items) { if (i.getArticleId() == article.id) { return i.amount; } } return 0; } public static class ShoppingCartItem { private int amount; private final long articleId; public ShoppingCartItem(int amount, Article article) { this.amount = amount; this.articleId = article.id; } public int getAmount() { return amount; } public void addAmount(int amount) { this.amount += amount; if (this.amount > MAX_ITEMS) { this.amount = MAX_ITEMS; } } public long getArticleId() { return articleId; } public void setAmount(Integer amount) { this.amount = amount; if (this.amount > MAX_ITEMS) { this.amount = MAX_ITEMS; } } } }