/**
 * 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.Map;

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

import olstore.domain.logic.OlstoreFacade;
import olstore.dto.AddressValue;
import olstore.dto.UserValue;

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

/**
 * @author glapouch
 *
 */
/**
 * @author glapouch
 *
 */
public class CreateUserController extends SimpleFormController {

    /** This form's olstore instance that is provided via Spring. */
    private OlstoreFacade olstore;

    /**
     * Sets up this form controller by providing the parent SimpleFormController
     * with details of what form backing object to use and which view to display.     *
     */
    public CreateUserController() {
            setSessionForm(true);
            setValidateOnBinding(false);
            setCommandClass(UserForm.class);
            setFormView("createUser");
            setSuccessView("createUser");
    }

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

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
     */
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        return new UserForm(new UserValue(), new AddressValue());
    }

    
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.mvc.BaseCommandController#onBindAndValidate(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.BindException)
     */
    protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
                    throws Exception {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user.fname", "FNAME_REQUIRED", "First name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user.lname", "LNAME_REQUIRED", "Last name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user.emailAdd", "EAMAIL_REQUIRED", "Email address is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user.phoneNum", "EAMAIL_REQUIRED", "Email address is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user.passwd", "PASS1_REQUIRED", "Password is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "passwordConfirm", "PASS2_REQUIRED", "Confirmation password is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user.username", "USERNAME_REQUIRED", "Username is required.");
        
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.country", "COUNTRY_REQUIRED", "Country name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.city", "CITY_REQUIRED", "Name of the city is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.postalCode", "CODE_REQUIRED", "Postal code is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.street1", "STREET_REQUIRED", "Street name and number are required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.province", "PROVINCE_REQUIRED", "Province is required.");
        
        UserForm form = (UserForm)command;
        if(!form.getPasswordConfirm().equals(form.getUser().getPasswd())) {
            errors.rejectValue("user.passwd", "PASS_NOTMATCH", "The two passwords you entered did not match.");
        }
        
        try {
            if(this.olstore.getUser(form.getUser().getUsername()) != null) {
                errors.rejectValue("user.username", "USERNAME_TAKEN", "The username you chose is already taken.");
            }
        } catch (Exception  e) {
            // if an exception was thrown because no such user was found then there is no problem
        }
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
     */
    protected Map referenceData(HttpServletRequest request) throws Exception {
        Map model = ControllerHelper.initModel(request, olstore);
        model.put("page_title", "User Registration - Olstore");
        return model;
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
     */
    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));
        
        UserForm user = (UserForm) command;
        try {
            this.olstore.createUser(user.getUser(), user.getAddress());
        }
        catch (Exception ex) {            
            model.put("error", "There was an error trying to create your account.");
            return showForm(request, response, errors, model);
        }
            
        return new ModelAndView(new RedirectView("/store/index.do", true));
    }
}