package com.ebpm.webdemo.struts;

import java.util.Collection;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.*;
import com.ebpm.webdemo.common.*;

/**
 * SimpleAction.java
 @author Daniel Seiler
 * Copyright © 2007 EBPM AG. All rights reserved
 *
 */
public class SimpleAction extends Action {

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

        String subaction = request.getParameter("subaction");
      // If user pressed 'Cancel' button,
        // return to home page
        if (isCancelled(request)) {
            return mapping.findForward("home");
        }
        
        if(subaction != null && "addperson".equals(subaction)) {
          // validate the data
          ActionErrors errors = validate((SimpleActionForm)form);
          if(errors.size() == 0) {
            // copy the form data into the person bean
            PersonBean personBean = new PersonBean();
            BeanUtils.copyProperties(personBean,form);
            // pass the data to the persistence layer
            PersonDAO.getInstance().addPerson(personBean);
          else {
            this.addErrors(request, errors);
          }
        }
        // get all the PersonBeans from the persistence layer
        Collection personBeans = PersonDAO.getInstance().getAllPersons();        
        request.setAttribute("personBeans", personBeans);        
        // forward to the result page
        return mapping.findForward("success");
    }
    
    public ActionErrors validate(
        SimpleActionForm form) {

        ActionErrors errors = new ActionErrors();

        // Name must be entered
        if ((form.getLastname() == null|| (form.getLastname().length() 1)) {
            errors.add("name"new ActionMessage("errors.name.required"));
        }
        // Secret Phrase must be entered
        if ((form.getFirstname() == null|| (form.getFirstname().length() 1)) {
            errors.add("secret"new ActionMessage("errors.secret.required"));
        }

        return (errors);
    }
}