package io.reactivesw.order.cart.application.service.update;

import io.reactivesw.common.exception.NotExistException;
import io.reactivesw.common.model.UpdateAction;
import io.reactivesw.order.cart.application.model.action.SetLineItemQuantity;
import io.reactivesw.order.cart.domain.entity.CartEntity;
import io.reactivesw.order.cart.domain.entity.value.LineItemValue;
import io.reactivesw.order.cart.infrastructure.util.CartUpdateActionUtils;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * Created by umasuo on 16/12/16.
 */
@Service(value = CartUpdateActionUtils.SET_LINE_ITEM_QUANTITY)
public class SetLineItemQuantityService extends CartUpdateService {

  /**
   * change line item quantity.
   *
   * @param entity E
   * @param action UpdateAction
   */
  @Override
  public void handle(CartEntity entity, UpdateAction action) {
    SetLineItemQuantity quantityAction = (SetLineItemQuantity) action;
    Integer quantity = quantityAction.getQuantity();
    String lineItemId = quantityAction.getLineItemId();

    LineItemValue item = this.getLineItem(entity, lineItemId);
    item.setQuantity(quantity);
  }

  /**
   * get line item from the cart.
   *
   * @param cart       cart
   * @param lineItemId line item id
   * @return LineItemValue
   */
  private LineItemValue getLineItem(CartEntity cart, String lineItemId) {
    Set<LineItemValue> lineItems = cart.getLineItems();
    LineItemValue item = lineItems.stream().filter(tmpItem -> tmpItem.getId() == lineItemId)
        .findAny().orElse(null);
    if (item == null) {
      throw new NotExistException("LineItem not existing when for cartId: " + lineItemId +
          "lineItemId:" + lineItemId);
    }
    return item;
  }
}

@@ -438,16 +438,61 @@
 nUtils;%0A
+import org.apache.commons.lang3.StringUtils;%0A
 import o
@@ -1509,16 +1509,25 @@
 .filter(
+%0A        
 tmpItem 
@@ -1529,16 +1529,35 @@
 Item -%3E 
+StringUtils.equals(
 tmpItem.
@@ -1563,19 +1563,17 @@
 .getId()
- ==
+,
  lineIte
@@ -1581,20 +1581,17 @@
 Id)%0A    
-    
+)
 .findAny
@@ -1709,26 +1709,28 @@
 Id: %22 + 
-lineItemId
+cart.getId()
  +%0A     

fix bug