package org.hso.ecommerce.entities.shop;

import java.util.ArrayList;

// Not a db entity. Just for session storage
public class ShoppingCart {

    private int revision;
    private ArrayList<ShoppingCartItem> items;

    public ShoppingCart() {
        revision = (int) Math.round(Math.random() * 0xFFFF);
        items = new ArrayList<>();
    }

    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));
    }

    private 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;
        }

        public long getArticleId() {
            return articleId;
        }
    }
}
