2020-05-05 17:24:25 +02:00
package org.hso.ecommerce.entities.shop ;
import java.util.ArrayList ;
2020-05-05 18:59:15 +02:00
import java.util.List ;
2020-05-05 17:24:25 +02:00
// Not a db entity. Just for session storage
public class ShoppingCart {
2020-05-05 22:56:12 +02:00
private final static int MAX_ITEMS = 10 ;
2020-05-05 17:24:25 +02:00
private int revision ;
private ArrayList < ShoppingCartItem > items ;
public ShoppingCart ( ) {
2020-05-05 22:56:12 +02:00
clear ( ) ;
}
public void clear ( ) {
2020-05-05 17:24:25 +02:00
items = new ArrayList < > ( ) ;
2020-05-05 22:56:12 +02:00
revision = ( int ) Math . round ( Math . random ( ) * 0xFFFF ) ;
2020-05-05 17:24:25 +02:00
}
2020-05-05 18:59:15 +02:00
public List < ShoppingCartItem > getItems ( ) {
return items ;
}
2020-05-05 17:24:25 +02:00
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 ) ) ;
}
2020-05-05 18:59:15 +02:00
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 ) ) ;
}
2020-05-05 22:56:12 +02:00
items . removeIf ( i - > i . getAmount ( ) < = 0 ) ;
2020-05-05 18:59:15 +02:00
}
2020-06-25 16:52:13 +02:00
public int getArticleCount ( Article article ) {
for ( ShoppingCartItem i : items ) {
if ( i . getArticleId ( ) = = article . id ) {
return i . amount ;
}
}
return 0 ;
}
2020-05-05 18:59:15 +02:00
public static class ShoppingCartItem {
2020-05-05 17:24:25 +02:00
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 ;
2020-05-05 22:56:12 +02:00
if ( this . amount > MAX_ITEMS ) {
this . amount = MAX_ITEMS ;
}
2020-05-05 17:24:25 +02:00
}
public long getArticleId ( ) {
return articleId ;
}
2020-05-05 18:59:15 +02:00
public void setAmount ( Integer amount ) {
this . amount = amount ;
2020-05-05 22:56:12 +02:00
if ( this . amount > MAX_ITEMS ) {
this . amount = MAX_ITEMS ;
}
2020-05-05 18:59:15 +02:00
}
2020-05-05 17:24:25 +02:00
}
}