package com.ibatis.jpetstore.presentation.action;

import com.ibatis.jpetstore.domain.*;
import com.ibatis.jpetstore.presentation.form.*;
import org.apache.struts.action.*;

import javax.servlet.http.*;
import java.util.*;

public class UpdateCartQuantitiesAction extends BaseAction {


  /* Public Methods */

  public ActionForward doPerform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    CartForm cartForm = (CartForm) form;

    Iterator cartItems = cartForm.getCart().getAllCartItems();
    while (cartItems.hasNext()) {
      CartItem cartItem = (CartItem) cartItems.next();
      String itemId = cartItem.getItem().getItemId();
      try {
        int quantity = Integer.parseInt(request.getParameter(itemId));
        cartForm.getCart().setQuantityByItemId(itemId, quantity);

        if (quantity < 1) {
          cartItems.remove();
        }
      } catch (Exception e) {
        //ignore on purpose
      }
    }

    return mapping.findForward("success");

  }


}
