/**
 * Created July 2011
 * Project: UI
 * Author: VHADMAHAGADORNB
 */
package gov.va.med.esr.ui.comms.action;

// Java classes
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;

import gov.va.med.esr.common.model.comms.HandBookMailQueue;
import gov.va.med.esr.common.model.lookup.HandBookMailStatusType;
import gov.va.med.esr.common.model.CommonEntityKeyFactory;
import gov.va.med.esr.ui.ApplicationConstants.MessageKeys;


public class HandbookDetailAction extends CommsLogAction {

   public HandbookDetailAction() {
      super();
   }

   public static final int MAX_ADD_COMMENTS_LENGTH=255;

   /**
    * Displays a search record
    *
    * @param mapping An action mapping
    * @param form A form bean
    * @param request A http request from an search.jsp page
    * @param response A http response to stream data to a next page
    * @return An action forward class encapsulating information about a next page
    * @throws java.lang.Exception Thrown if failed to process
    */
   public ActionForward display( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response )
       throws Exception {

      return mapping.findForward("detail");
   }

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

        return mapping.findForward("commsLog");
    }

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

	   // Ensure we have a valid search form
	   CommsLogForm commsLogForm = getCommsLogForm(form);

	   HandBookMailQueue log =
		   getHandBookService().getHandbookMailQueueEntry(CommonEntityKeyFactory.createHandBookMailQueueEntityKey(
				   commsLogForm.getSelectedCommsLogId()));	   

	   if(StringUtils.isNotBlank(commsLogForm.getNewComment())) {
		   // this is done differently from CommsLog where each new comment is appended to any previous comment and 
		   // stored in a single column.  Here we take advantage of the fact that each updated record becomes a new row in the
		   // history table. So we simply store each new comment in the actionComment field.  All previous comments will be in their
		   // own records in the history table -- no need to keep track of them here.
		   log.setActionComment(commsLogForm.getNewComment());
	   }

	   if(commsLogForm.isCancelMailing())
	   {
		   getHandBookService().changeHandbookMailingStatus(log, (HandBookMailStatusType)getLookupCacheService().getByCodeFromCache(HandBookMailStatusType.class,
				   HandBookMailStatusType.CANCEL_BY_HEC.getName()));
	   }

	   getHandBookService().updateRemarks(log);

	   return mapping.findForward("commsLog");
   }

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() {
        // Check for required components here
    }

    protected Map getKeyMethodMap()
    {

        Map map = new HashMap();

        map.put("title.commsDetail", "display");
        map.put("button.update","updateComment");
        map.put("button.cancel","cancel");
        return map;
    }
    /**
     * This method validates length of the commets field.
     * if it is greater than MAX_COMMENTS_LENGTH, sets error message and populates
     * required fields in the form to display.
     *
     */
    public ActionMessages validateAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	CommsLogForm commsLogForm = getCommsLogForm(form);

    	if(StringUtils.trimToEmpty(commsLogForm.getNewComment()).length()>(MAX_ADD_COMMENTS_LENGTH))
    	{
    		MessageResources messageResources = commsLogForm.getResources(request);
    		populateActionForm(commsLogForm, request, HANDBOOK);
            ActionMessages messages = commsLogForm.getActionMessages(request);
            String label = messageResources.getMessage("commsLog.comments");
            messages.add("newComment",new ActionMessage(MessageKeys.ERRORS_MAXLENGTH,label,new Integer(MAX_ADD_COMMENTS_LENGTH).toString()));
            return messages;
    	}
    	return super.validateAction(mapping, form, request, response);
    }
}