/**
 * Copyright (c) 2006 Red Hat, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Component of: Red Hat Application Server
 * 
 * Initial Developers: Greg Lapouchnian
 *                     Patrick Smith
 *
 */

package olstore.controller;

import java.util.Iterator;
import java.util.Map;

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

import olstore.domain.logic.OlstoreFacade;
import olstore.dto.OrderEntry;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

/**
 * A controller to handle the update order action.
 */
public class UpdateOrderController extends SimpleFormController {

    // The olstore bean instance provided via Spring.
    private OlstoreFacade olstore;

    /**
     * Create a new form controller and set the form views as well as the
     * backing object class.
     */
    public UpdateOrderController() {
            setSessionForm(true);
            setValidateOnBinding(false);
            setCommandClass(OrderFormHelper.class);
            setFormView("updateOrder");
            setSuccessView("updateOrder");
    }

    /**
     * Spring injection setter method.
     * @param olstore the bean instance that is injected via Spring.
     */
    public void setOlstore(OlstoreFacade olstore) {
        this.olstore = olstore;
    }

    /**
     * Return a new helper object that will be used as this form's backing object.
     * @param request the HttpServletRequest.
     * @return a backing object for this form.
     */
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
            return new OrderFormHelper(olstore.findOrdersForUpdate());
    }

    /**
     * This form's validation method to handle the backing object's fields.
     * @param request the HttpServletRequest.
     * @param command the form's backing object.
     * @param errors the reported from the validation.
     */
    protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
                    throws Exception {
       // ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fname", "FNAME_REQUIRED", "First name is required.");
      //  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lname", "LNAME_REQUIRED", "Last name is required.");
        // TODO 
    }

    /**
     * The map used in this form's view.
     * @param request the HttpServletRequest.
     * @return a map representing the data for this form's view.
     */
    protected Map referenceData(HttpServletRequest request) throws Exception {
        Map model = ControllerHelper.initModel(request, olstore);
        model.put("page_title", "Edit Order Status - Olstore");
        return model;
    }

    /**
     * Handles the submission of this form.
     * 
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param command this forms backing object.
     * @param errors this form's errors as reported via validation.
     * @return a new model and view to represent this form.
     */
    protected ModelAndView onSubmit(
                    HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
                    throws Exception {
        // supply the errors to the view inside the model map
        Map model = errors.getModel();
        // add the reference data once again so it will continue to be displayed
        model.putAll(referenceData(request));
        
        OrderFormHelper orders = (OrderFormHelper) command;
        try {
            Iterator orderIt = orders.getOrdersList().iterator();
            while (orderIt.hasNext()) {
                OrderEntry order = (OrderEntry) orderIt.next();
                olstore.setStatus(order.getOrderId(), order.getOrderStatus());
            }
        }
        catch (Exception ex) {            
            model.put("error", "There was an error trying to update order status.");
            return showForm(request, response, errors, model);
        }
            
        model.put("message", "Your changes have been successfully recorded.");
        model.put("command", formBackingObject(request));
        return new ModelAndView("updateOrder", model);
    }
}