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

// Java Classes
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Library Classes
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

// Framework Classes
import gov.va.med.fw.service.ServiceConfigurationException;
import gov.va.med.fw.util.StringUtils;

// ESR Classes
import gov.va.med.esr.ui.common.action.PersonAbstractAction;
import gov.va.med.esr.ui.common.util.DateUtils;
import gov.va.med.esr.ui.util.SessionManager;
import gov.va.med.esr.service.MessagingService;
import gov.va.med.esr.service.LookupService;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.messaging.SiteIdentity;
import gov.va.med.esr.common.model.lookup.VAFacility;

/**
 * This struts action is used to support the send query message Z07 page.
 *
 * @author Andrew Pach
 * @version 3.0
 */
public class SendQueryMessageZ07Action extends PersonAbstractAction
{
    // Struts forwards
    public static final String FORWARD_SEND_QUERY_MESSAGE_Z07 = "sendQueryMessageZ07";
    public static final String FORWARD_SEND_BROKER_QUERY_MESSAGE = "sendMsdsQueryMessage";
    public static final String FORWARD_FACILITY = "facility";
    public static final String FORWARD_FACILITY_SENT_SUCCESSFULLY = "facility.sent.successfully";
    public static final String FORWARD_FACILITY_NO_FACILITY = "facility.no.facility";

    /**
     * Default constructor.
     */
    public SendQueryMessageZ07Action()
    {
        super();
    }

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

    /**
     * Displays the Demographics Addresses page.
     *
     * @param mapping Struts action mapping for this action
     * @param form 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 display(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        SendQueryMessageZ07Form z07Form = getSendQueryMessageZ07Form(form);

        // Get the Person object from the cache
        Person person = getSelectedPerson(request);

        // Populate the list of VAFacility records for this veteran
        List siteList = (List)SessionManager.getQRYZ07FacilityList(request);
        if (siteList == null)
        {
            MessagingService messagingService = getMessagingService();
            Set siteIdentities = messagingService.findSitesOfRecord(person);
            List sites = new ArrayList();
            for (Iterator iterator = siteIdentities.iterator(); iterator.hasNext();)
            {
                SiteIdentity siteIdentity = (SiteIdentity)iterator.next();
                VAFacility vaFacility = siteIdentity.getVaFacility();
                sites.add(vaFacility);
            }

            // If there are no sites associated with this veteran, add an error message and forward back to the
            // facilities page
            if (sites.isEmpty())
            {
                return mapping.findForward(FORWARD_FACILITY_NO_FACILITY);
            }

            // Sites have to go in session or the list will disappear if a declarative validation error occurs
            SessionManager.setQRYZ07FacilityList(request, sites);
        }

        // Default the year to the current year if one wasn't specified
        if (StringUtils.isBlank(z07Form.getIncomeYear()))
        {
            z07Form.setIncomeYear(String.valueOf(DateUtils.getCurrentYear()));
        }

        return mapping.findForward(FORWARD_SEND_QUERY_MESSAGE_Z07);
    }

    /**
     * Resets the data to its original state.
     *
     * @param mapping Struts action mapping for this action
     * @param form 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 reset(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        SendQueryMessageZ07Form z07Form = getSendQueryMessageZ07Form(form);
        z07Form.reset(mapping, request);
        return display(mapping, form, request, response);
    }

    /**
     * Initiates the sending of a QRYZ07 message.
     * This method assumes that the form has been successfully validated.  That means that the VAFacility code
     * is valid and that the income year is a valid Integer.
     *
     * @param mapping Struts action mapping for this action
     * @param form 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 sendMessage(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        SendQueryMessageZ07Form z07Form = getSendQueryMessageZ07Form(form);

        // Get the selected person
        Person person = getSelectedPerson(request);

        // Get the selected VAFacility
        LookupService lookupService = getLookupService();
        VAFacility facility = lookupService.getVaFacilityByCode(z07Form.getSite());

        // Send the message
        MessagingService messagingService = getMessagingService();
        messagingService.triggerQRYZ07(person, facility, new Integer(z07Form.getIncomeYear()));

        // Forward back to the Facilities page
        return mapping.findForward(FORWARD_FACILITY_SENT_SUCCESSFULLY);
    }

    /**
     * Cancels this page and goes to the veteran overview screen.
     *
     * @param mapping Struts action mapping for this action
     * @param form 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 cancel(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        return mapping.findForward(FORWARD_FACILITY);
    }

    /**
     * Checks to ensure the passed in ActionForm is not null and of the correct type.
     *
     * @param form The struts form to check
     *
     * @return The passed in form type-casted to a DemographicAddressesForm
     * @throws gov.va.med.fw.service.ServiceConfigurationException if the form is null or of an incorrect type.
     */
    protected SendQueryMessageZ07Form getSendQueryMessageZ07Form(ActionForm form)
        throws ServiceConfigurationException
    {
        SendQueryMessageZ07Form z07Form =
            (form instanceof SendQueryMessageZ07Form) ? (SendQueryMessageZ07Form)form : null;
        if (z07Form == null)
        {
            throw new ServiceConfigurationException("SendQueryMessageZ07Form not properly configured.");
        }
        return z07Form;
    }
    
    //  Meena TODO the meat to the triggerBroker needs to be added
    public ActionForward sendBrokerMessage(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
        {
            
            // Get the selected person
            Person person = getSelectedPerson(request);

            // Send the message
            MessagingService messagingService = getMessagingService();
            messagingService.processTriggerBroker(person) ;

            // Forward back to the Facilities page
            return mapping.findForward(FORWARD_FACILITY_SENT_SUCCESSFULLY);
        }
    
    public ActionForward displayConfirmation(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
        {
            return mapping.findForward(FORWARD_SEND_BROKER_QUERY_MESSAGE);
        }

    /**
     * Initialize and get the Struts lookup dispatch method map hashmap.
     *
     * @return the method map
     * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
     */
    protected Map getKeyMethodMap()
    {
        Map map = new HashMap();
        map.put("button.send", "sendMessage");
        map.put("button.cancel", "cancel");
        map.put("button.reset", "reset");
        map.put("link.name.sendQueryZ07", "display");
        map.put("button.confirm", "sendBrokerMessage");
        map.put("link.name.sendMsdsQuery", "displayConfirmation");
        return map;
    }
}