/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.ui.facility.action;

// Java Classes
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// Library Classes
import net.mlw.vlh.ValueList;

import org.apache.commons.lang.Validate;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

// Framework Classes
import gov.va.med.fw.ui.struts.ValueListActionUtils;
import gov.va.med.fw.ui.valuelist.MaxRecordsExceededValueListException;
import gov.va.med.fw.util.StringUtils;

// ESR Classes
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.messaging.ArchivedMessageLogEntry;
import gov.va.med.esr.ui.ApplicationConstants;
import gov.va.med.esr.ui.common.action.PersonAbstractAction;
import gov.va.med.esr.ui.message.action.MessageConstants;
import gov.va.med.esr.ui.message.action.MessageSearchForm;

/**
 * @author Madhu Katikala, Muddaiah Ranga
 */
public class HL7MessageAction extends PersonAbstractAction implements FacilityConstants {
	
	/**
     * Displays all the messages log entries for the site/veteran.
     * 
     * @param mapping
     *           Struts action mapping for this action
     * @param actionForm
     *           Struts form bean for this action
     * @param request
     *           The Http Request
     * @param response
     *           The Http Response
     *           
     * @return A struts action forward for where we will go next.
     * @throws Exception
     *            If there are any errors during processing.
     */
    public ActionForward chooseDisplayMessages(ActionMapping mapping,
                                            ActionForm actionForm, 
                                            HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        
    	ActionForward forward = null;
        HttpSession session = request.getSession();
	    if(session.getAttribute("selectedMessage") != null && (session.getAttribute("selectedMessage").getClass().equals(ArchivedMessageLogEntry.class))){
	    	forward = displayArchivedMessages(mapping,actionForm,request,response);	
	    }
	    else{
	    	forward = displayMessages(mapping,actionForm,request,response);
	    }
	    return forward;    
	    
    }
    
    /**
     * Displays all the messages log entries for the site/veteran.
     * 
     * @param mapping
     *           Struts action mapping for this action
     * @param actionForm
     *           Struts form bean for this action
     * @param request
     *           The Http Request
     * @param response
     *           The Http Response
     *           
     * @return A struts action forward for where we will go next.
     * @throws Exception
     *            If there are any errors during processing.
     */
    public ActionForward displayMessages(ActionMapping mapping,
                                            ActionForm actionForm, 
                                            HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        
        
        HttpSession session = request.getSession();
	    if(session.getAttribute("selectedMessage") != null){	    	
	    	session.removeAttribute("selectedMessage");	    	
	    }
    	String selectedSiteId = request.getParameter(MessageConstants.SELECTED_SITE_ID);
        ActionForward forward = StringUtils.isNotEmpty(selectedSiteId) ? mapping.findForward(SITE_MESSAGES) : mapping.findForward(MESSAGES);
        try {
            MessageSearchForm form = (MessageSearchForm)actionForm;
            form.clear();
            form.setPersonId(getSelectedPersonId(request));
            
            if(StringUtils.isNotEmpty(selectedSiteId)) {
                form.setFacility(selectedSiteId);
                VAFacility facility = (VAFacility)this.getLookupCacheService().getByCodeFromCache(VAFacility.class,selectedSiteId);
                request.setAttribute(MessageConstants.SELECTED_SITE_ID,selectedSiteId);
                request.setAttribute(MessageConstants.SELECTED_SITE,facility);
            }
        
            // Get the value list information
            ValueList valueList = ValueListActionUtils.getValueList(form,request,MessageConstants.MESSAGE_SEARCH_TABLE_ID,VETERAN_MESSAGE_SEARCH_ADAPTER);
            ValueListActionUtils.setValueList(request,valueList,MessageConstants.VALUE_LIST);
            if(valueList == null || !valueList.hasNext()) {
                forward = mapping.findForward(FACILITY);
                addInformationMessage(request,ApplicationConstants.MessageKeys.ERRORS_SEARCH_NORESULT);
            }
        } catch (MaxRecordsExceededValueListException ex) {
            // The search exceeded the maximum number of records allowed.
            addActionMessage(request, new ActionMessage(ApplicationConstants.MessageKeys.ERRORS_MAX_RECORDS_EXCEEDED,
                new Integer(ex.getTotalRecords()), new Integer(ex.getRecordLimit())));
        }
        return forward;
    }
    
    /**
     * Displays all the messages log entries for the site/veteran.
     * 
     * @param mapping
     *           Struts action mapping for this action
     * @param actionForm
     *           Struts form bean for this action
     * @param request
     *           The Http Request
     * @param response
     *           The Http Response
     *           
     * @return A struts action forward for where we will go next.
     * @throws Exception
     *            If there are any errors during processing.
     */
    public ActionForward displayArchivedMessages(ActionMapping mapping,
                                            ActionForm actionForm, 
                                            HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
    	
    	HttpSession session = request.getSession();
	    if(session.getAttribute("selectedMessage") != null){	    	
	    	session.removeAttribute("selectedMessage");	    		    	
	    }
        String selectedSiteId = request.getParameter(MessageConstants.SELECTED_SITE_ID);
        ActionForward forward = StringUtils.isNotEmpty(selectedSiteId) ? mapping.findForward(SITE_MESSAGES) : mapping.findForward(ARCHIVED_MESSAGES);
        try {
            MessageSearchForm form = (MessageSearchForm)actionForm;
            form.clear();
            form.setPersonId(getSelectedPersonId(request));
            
            if(StringUtils.isNotEmpty(selectedSiteId)) {
                form.setFacility(selectedSiteId);
                VAFacility facility = (VAFacility)this.getLookupCacheService().getByCodeFromCache(VAFacility.class,selectedSiteId);
                request.setAttribute(MessageConstants.SELECTED_SITE_ID,selectedSiteId);
                request.setAttribute(MessageConstants.SELECTED_SITE,facility);
            }
        
            // Get the value list information
            ValueList valueList = ValueListActionUtils.getValueList(form,request,MessageConstants.ARCHIVED_MESSAGE_SEARCH_TABLE_ID,ARCHIVED_MESSAGE_SEARCH_ADAPTER);
            ValueListActionUtils.setValueList(request,valueList,MessageConstants.VALUE_LIST);
            if(valueList == null || !valueList.hasNext()) {
                forward = mapping.findForward(FACILITY);
                addInformationMessage(request,ApplicationConstants.MessageKeys.ERRORS_SEARCH_NORESULT);
            }
        } catch (MaxRecordsExceededValueListException ex) {
            // The search exceeded the maximum number of records allowed.
            addActionMessage(request, new ActionMessage(ApplicationConstants.MessageKeys.ERRORS_MAX_RECORDS_EXCEEDED,
                new Integer(ex.getTotalRecords()), new Integer(ex.getRecordLimit())));
        }
        return forward;
    }

    /**
     * Retransmit a message.
     * 
     * @param mapping
     *           Struts action mapping for this action
     * @param actionForm
     *           Struts form bean for this action
     * @param request
     *           The Http Request
     * @param response
     *           The Http Response
     *           
     * @return A struts action forward for where we will go next.
     * @throws Exception
     *            If there are any errors during processing.
     */
    public ActionForward retransmit(ActionMapping mapping, ActionForm actionForm,
                                    HttpServletRequest request, 
                                    HttpServletResponse response) throws Exception {

        String messageLogId = request.getParameter(ApplicationConstants.JSPParameters.SELECTED_MSG_ID_PARAM);
        if(StringUtils.isNotEmpty(messageLogId)) {
            this.getMessagingService().triggerRetransmission(new BigDecimal(messageLogId));
            addInformationMessage(request,MessageConstants.MESSAGE_RETRANSMITTED);
        }
        String selectedMsgId = request.getParameter(MessageConstants.SELECTED_SITE_ID);
        if(StringUtils.isNotEmpty(selectedMsgId)) {
            request.setAttribute(MessageConstants.SELECTED_SITE_ID,selectedMsgId);
        }
        return displayMessages(mapping,actionForm,request,response);
    }    
    
    
    protected Map getKeyMethodMap()
    {
        Map map = new HashMap();
        map.put("link.displayMessages", "displayMessages");
        map.put("link.displayArchivedMessages", "displayArchivedMessages");
        map.put("buttom.retransmit", "retransmit");
        map.put("link.displayChooseMessages", "chooseDisplayMessages");
        return map;
    }

    public void afterPropertiesSet() throws Exception {
        Validate.notNull(this.getMessagingService(),"Missing required messaging service");
    }
}