package com.ibatis.jpetstore.presentation.action;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ibatis.db.dao.DaoException;
import com.ibatis.jpetstore.domain.Account;
import com.ibatis.jpetstore.domain.LineItem;
import com.ibatis.jpetstore.domain.Order;
import com.ibatis.jpetstore.presentation.form.OrderForm;

public class NewOrderAction extends SecureBaseAction {

  /* Public Methods */

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

	OrderForm orderForm = (OrderForm) form;

	if (orderForm.isShippingAddressRequired()) {
		return mapping.findForward("shipping");
		//    } else if (!orderForm.isConfirmed()) {
		//      return mapping.findForward("confirm");
	} else if (orderForm.getOrder() != null) {
		Order order = orderForm.getOrder();
		System.out.println(
			"orderForm.isUseMileage()=" + orderForm.isUseMileage());
		double newMileage = 0;
		Account account = petStore.getAccount(order.getUsername());
		if (orderForm.isUseMileage()) {
			double mileage = account.getMileage().doubleValue();
			double totalPrice = order.getTotalPrice().doubleValue();

			order.setMileage(
				new BigDecimal(totalPrice >= mileage ? mileage : totalPrice));
			order.setTotalPrice(
				new BigDecimal(
					totalPrice >= mileage ? totalPrice - mileage : 0));
			newMileage = account.getMileage().doubleValue() - mileage;

		} else {

			List items = order.getLineItems();
			for (int i = 0; i < items.size(); i++) {
				LineItem item = (LineItem) items.get(i);
				item.setMileage(new BigDecimal(0));
			}

			newMileage =
				account.getMileage().doubleValue()
					+ order.getMileage().doubleValue();

			order.setMileage(new BigDecimal(0));

		}

		account.setMileage(new BigDecimal(newMileage));
		petStore.updateAccount(account);

		petStore.insertOrder(order);

		request.getSession().removeAttribute("workingOrderForm");
		request.getSession().removeAttribute("cartForm");

		request.setAttribute("order", order);
		request.setAttribute("itemList", order.getLineItems());

		request.setAttribute(
			"message",
			"Thank you, your order has been submitted.");

		return mapping.findForward("success");
	} else {
		request.setAttribute(
			"message",
			"An error occurred processing your order (order was null).");
		return mapping.findForward("failure");
	}

}
}
