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

// Java classes
import gov.va.med.esr.common.model.lookup.Country;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.financials.*;
import gov.va.med.esr.ui.common.action.AddressForm;
import gov.va.med.esr.ui.demographic.action.DemographicPersonalForm;
import gov.va.med.esr.ui.util.SessionManager;

import java.util.Map;
import java.util.HashMap;
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;
import gov.va.med.esr.ui.common.action.AddressValidationAction;
// Framework classes

// ESR classes

/**
 * This struts action is used to support the financials dependent add page.
 *
 * @author Andrew Pach
 * @version 3.0
 */
public class FinancialsDependentAddAction extends FinancialsDependentAction
{
    // Struts forwards
    public static final String FORWARD_FINANCIALS_DEPENDENT_ADD = "financialsDependentAdd";
    public static final String FORWARD_FINANCIALS_SPOUSE_ADD = "financialsSpouseAdd";

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

    /**
     * Displays the Demographics Personal 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 displayAddChildPage(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
    	boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
    	FinancialsDependentForm dependentForm = getFinancialsDependentForm(form);
    	dependentForm.setAddAPerson(isAddAPerson);
    	dependentForm.setSpouseInd(false);
    	
    	return mapping.findForward(FORWARD_FINANCIALS_DEPENDENT_ADD);
    }
    
    /**
     * Displays the Demographics Personal 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 displayAddSpousePage(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
    	boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
    	FinancialsDependentForm dependentForm = getFinancialsDependentForm(form);
    	dependentForm.setAddAPerson(isAddAPerson);
    	
    	dependentForm.setSpouseInd(true);
    	return mapping.findForward(FORWARD_FINANCIALS_SPOUSE_ADD);
    }

    /**
     * Handles an optimistic lock exception by resetting the form and redisplaying the 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.
     */
    protected ActionForward handleOptimisticLockException(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        FinancialsDependentForm dependentForm = getFinancialsDependentForm(form);
        boolean spouseInd = dependentForm.getSpouseInd();
    	form.reset(mapping,request);
        if (spouseInd)
        {
            return displayAddSpousePage(mapping,form,request,response);
        }
        else
        {
            return displayAddChildPage(mapping,form,request,response);
        }
    }

    /**
     * Updates the personal information.
     *
     * @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 add(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
    	FinancialsDependentForm dependentForm = getFinancialsDependentForm(form);
  		
    	boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
        dependentForm.setAddAPerson(isAddAPerson);
        
    	// Get the Person object from the cache
        Person person = getSelectedPerson(request);
        
        // Get the income year from the cache and set it on the form
        Integer incomeYear = getSelectedIncomeYear(request);

		Person clonePerson = (Person)person.clone();
		FinancialStatement fstmt = clonePerson.getFinancialStatement(incomeYear);
		if (fstmt == null)
        {
			fstmt = new FinancialStatement();
			fstmt.setIsPost2005Format(Boolean.TRUE);
            clonePerson.setFinancialStatement(incomeYear, fstmt);
        }

     	if(dependentForm.getSpouseInd()) {
            //If there is already an active spouse display an error message.
     	    if(!dependentForm.isSpouseHasInactiveDate() && isPersonHasActiveSpouse(incomeYear,person)) {
               addActionMessageForField(request,SPOUSE_CANNOT_BE_ADDED,SPOUSE_INACTIVE_DATE);
               return mapping.findForward(FORWARD_FINANCIALS_SPOUSE_ADD);
     	    }
      		// CCR10471
      		if (isAddAPerson){
      			ActionForward overviewSuccessForward =
      				new ActionForward(mapping.findForward(FORWARD_FINANCIALS_SPOUSE_ADD));
      			ActionForward samePageForward = mapping.findForward(FORWARD_FINANCIALS_SPOUSE_ADD);
	         
	            // Perform US extra validation
	            if (Country.isUSAddress(dependentForm.getCountry()))
	            {
	                // Validate the state
	                if (!stateValid(dependentForm, AddressForm.class, STATE_FIELD, overviewSuccessForward,
	                    request))
	                {
	                    return samePageForward;
	                }
	
	                // Validate the zip code matches the city/state
	                if (!zipCodeMatchesCityAndState(dependentForm, AddressForm.class, CITY_FIELD, STATE_FIELD,
	                    ZIPCODE_FIELD, request))
	                {
	                    return samePageForward;
	                }
	            }
	            SpouseFinancials spouseFinancials = new SpouseFinancials();
	     		fstmt.addSpouseFinancials(spouseFinancials);
	      		conversionService.convert(dependentForm, spouseFinancials);
	      		Person updatedPerson = spouseFinancials.getPerson();
	      		updateSelectedPerson(request,updatedPerson);
	            // return overviewSuccessForward;
      		}
      		else {
	      		SpouseFinancials spouseFinancials = new SpouseFinancials();
	     		fstmt.addSpouseFinancials(spouseFinancials);
	      		conversionService.convert(dependentForm, spouseFinancials);	
	     		Person updatedPerson = this.getFinancialsService().updateSpouseFinancials(incomeYear,spouseFinancials,clonePerson);
	     		updateSelectedPerson(request,updatedPerson);
      		}
    	}
    	else {
    		DependentFinancials dependentFinancials = new DependentFinancials();
    		fstmt.addDependentFinancials(dependentFinancials);
    		conversionService.convert(dependentForm,dependentFinancials);
    		
            if (isAddAPerson){
            	Person updatedPerson = dependentFinancials.getPerson();
	      		updateSelectedPerson(request,updatedPerson);
            }
            else{
            	Person updatedPerson =  this.getFinancialsService().updateDependentFinancials(incomeYear,dependentFinancials,clonePerson);
            	updateSelectedPerson(request,updatedPerson);
            }
    	}
    	return mapping.findForward(FORWARD_FINANCIALS_DEPENDENT_OVERVIEW_WITH_MSG);
    }

    /**
     * Cancels this page and goes to the demographics 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_FINANCIALS_DEPENDENT_OVERVIEW);
    }

    /**
     * Initialize and get the Struts lookup dispatch method map hashmap.
     *
     * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
     * @return the method map
     */
   protected Map getKeyMethodMap()
   {
		if(keyMethodMap == null)
		{
			keyMethodMap = new HashMap();
			keyMethodMap.put("button.add", "add");
			keyMethodMap.put("button.cancel", "cancel");
			keyMethodMap.put("button.addDepChild","displayAddChildPage");
			keyMethodMap.put("button.addDepSpouse","displayAddSpousePage");
		}
	    return keyMethodMap;
   }
}