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

import gov.va.med.esr.common.model.person.Association;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.lookup.Country;
import gov.va.med.esr.ui.common.action.AddressForm;
import gov.va.med.fw.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * Action handler for updating an existing Associate.
 * 
 * @author Muddaiah Ranga
 * @version 3.0
 */
public class PersonAssociationUpdateAction extends PersonAssociationAction
{
    /**
     * Displays form to update an existing Associate.
     *
     * @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 display(ActionMapping mapping, 
			 					 ActionForm actionForm,
								 HttpServletRequest request, 
								 HttpServletResponse response) 
	throws Exception 
	{
		PersonAssociationInfoForm form = (PersonAssociationInfoForm)actionForm;
		Person person = getSelectedPerson(request);

		String associateId = form.getAssociateId();
		if(StringUtils.isNotEmpty(associateId))
		{
			Association association = getAssociationById(person,associateId);
			if(association != null)
			{
				request.setAttribute(ASSOCIATE_KEY,association);
				conversionService.convert(association,form);
			}
			else
			{
				addActionMessage(request,MESSAGE_ASSOCIATE_NOT_FOUND);
			}
		}
		return mapping.findForward(DISPLAY);
	}
	
    /**
     * Updates an existing Associate.
     *
     * @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 updateAssociate(ActionMapping mapping, 
			   							   ActionForm actionForm,
										   HttpServletRequest request, 
										   HttpServletResponse response) 
	throws Exception 
	{
		PersonAssociationInfoForm form = (PersonAssociationInfoForm)actionForm;
	    Person person = getSelectedPerson(request);

        // Create some action forwards
        ActionForward overviewSuccessForward =
            new ActionForward(mapping.findForward(OVERVIEW_WITH_MESSAGE));
        ActionForward displayForward = mapping.findForward(DISPLAY);

        // Perform US extra validation
        if (Country.isUSAddress(form.getCountry()))
        {
            // Validate the state
            if (!stateValid(form, AddressForm.class, STATE_FIELD, overviewSuccessForward, request))
            {
                return displayForward;
            }

            // Validate the zip code matches the city/state
            if (!zipCodeMatchesCityAndState(form, AddressForm.class, CITY_FIELD, STATE_FIELD, ZIPCODE_FIELD, request))
            {
                return displayForward;
            }
        }

        String associateId = form.getAssociateId();
	    if(StringUtils.isNotEmpty(associateId))
	    {
	        Person updatedPerson = (Person)person.clone();
	        Association association = getAssociationById(updatedPerson,associateId);
	        if(association != null)
	        {
	            conversionService.convert(form,association);
	            updatedPerson =  this.getAssociationService().updateAssociation(updatedPerson,association);
	            updateSelectedPerson(request,updatedPerson);
	        }
	        else
	        {
	            addActionMessage(request,MESSAGE_ASSOCIATE_NOT_FOUND);
	        }
	    }

        return overviewSuccessForward;
	}
	
	protected ActionForward handleOptimisticLockException(
			ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		form.reset(mapping,request);
		return display(mapping,form,request,response);
	}
	protected Map getKeyMethodMap() 
	{
		if(keyMethodMap == null)
		{
			keyMethodMap = new HashMap();
			keyMethodMap.put("button.display","display");
			keyMethodMap.put("button.reset","display");
			keyMethodMap.put("button.update","updateAssociate");
			keyMethodMap.put("button.cancel", "cancel");
		}
        return keyMethodMap;
    }
}
