/**
 * Created on 4:44:56 PM Jan 11, 2005
 * Project: UI
 */
package gov.va.med.esr.ui.comms.action;

// Java classes
import java.util.HashMap;
import java.util.Iterator;
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.CommsLogEntry;
import gov.va.med.esr.common.model.comms.HecRejectReason;
import gov.va.med.esr.common.model.lookup.ComMailingStatusType;
import gov.va.med.esr.common.model.CommonEntityKeyFactory;
import gov.va.med.esr.ui.ApplicationConstants.MessageKeys;


public class CommsLogDetailAction extends CommsLogAction {

   public CommsLogDetailAction() {
      super();
   }

   public static final int MAX_COMMENTS_LENGTH=4000;
   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);
    CommsLogEntry log = getCommsLogService().getCommsLogEntry(CommonEntityKeyFactory.createCommsLogEntryEntityKey(
        commsLogForm.getSelectedCommsLogId()));

    if(StringUtils.isNotBlank(commsLogForm.getNewComment())) {

    	String comment = log.getActionComment();
    	int currentLength = (comment != null)?comment.length():0;
        log.addActionComment(formatComment(commsLogForm.getNewComment(), request));
        String updatedComment = log.getActionComment();
        int updatedLength = updatedComment.length();
        int newLength = commsLogForm.getNewComment().length();

       	if(updatedLength > MAX_COMMENTS_LENGTH) {
            int maxCommentsLength = (MAX_COMMENTS_LENGTH-currentLength) - (updatedLength - currentLength - newLength);
            maxCommentsLength = (maxCommentsLength < 0)?0:maxCommentsLength;

       		MessageResources messageResources = commsLogForm.getResources(request);
            ActionMessages messages = commsLogForm.getActionMessages(request);
            String label = messageResources.getMessage("commsLog.comments");
            messages.add("newComment",new ActionMessage(MessageKeys.ERRORS_MAXLENGTH,label,new Integer(maxCommentsLength).toString()));
            return mapping.findForward("detail");
       	}
    }

    if(commsLogForm.isCancelMailing())
    {
        ComMailingStatusType status = (ComMailingStatusType)
        getLookupCacheService().getByCodeFromCache(ComMailingStatusType.class,
        ComMailingStatusType.CANCEL_BY_HEC.getName());

        log.addMailingStatus(status);
    }
    else if(commsLogForm.isReturnedByPostOffice())
    {
        ComMailingStatusType status = (ComMailingStatusType)
        getLookupCacheService().getByCodeFromCache(ComMailingStatusType.class,
        ComMailingStatusType.RETURN_BY_POST_OFFICE.getName());

        log.addMailingStatus(status);
    }

    CommsLogEntry newLog = getCommsLogService().updateCommunicationLog(log);
    commsLogForm.setSelectedCommsLog(newLog);

    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+4))
    	{
    		MessageResources messageResources = commsLogForm.getResources(request);
    		populateActionForm(commsLogForm, request, NON_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);
    }
}