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

// Java classes
import gov.va.med.esr.common.model.financials.DependentFinancials;
import gov.va.med.esr.common.model.financials.FinancialStatement;
import gov.va.med.esr.common.model.financials.SpouseFinancials;
import gov.va.med.esr.common.model.lookup.Country;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.ui.common.action.AddressForm;
import gov.va.med.esr.ui.util.SessionManager;
import gov.va.med.fw.model.EntityKey;
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;

/**
 * This struts action is used to support the financials dependent edit page.
 *
 * @author Andrew Pach
 * @version 3.0
 */
public class FinancialsDependentEditAction extends FinancialsDependentAction
{
    // Struts forwards
    public static final String FORWARD_FINANCIALS_DEPENDENT_EDIT = "financialsDependentEdit";
    public static final String FORWARD_FINANCIALS_SPOUSE_EDIT = "financialsSpouseEdit";

    /**
     * Default constructor.
     */
    public FinancialsDependentEditAction()
    {
        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 display(ActionMapping mapping, 
                                 ActionForm form,
                                 HttpServletRequest request, 
                                 HttpServletResponse response) throws Exception  {
        ActionForward forward = null;
    	FinancialsDependentForm dependentForm = (FinancialsDependentForm)form;
		
    	boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
    	dependentForm.setAddAPerson(isAddAPerson);
    	
        // Get the income year from the cache and set it on the form
        Integer incomeYear = getSelectedIncomeYear(request);
        dependentForm.setIncomeYear(String.valueOf(incomeYear));

    	String dependentId = dependentForm.getDependentId();
		if(incomeYear != null && StringUtils.isNotEmpty(dependentId)) {
	   		// Get the Person object from the cache
	        Person person = getSelectedPerson(request);
	        SpouseFinancials spouseFin = (SpouseFinancials)getSpouseFinancialsById(person, dependentId, incomeYear);
            if(spouseFin != null) {
                conversionService.convert(spouseFin,dependentForm);
                forward = mapping.findForward(FORWARD_FINANCIALS_SPOUSE_EDIT);
            } else {
                DependentFinancials depFin = (DependentFinancials)getDependentFinancialsById(person, dependentId, incomeYear);
                conversionService.convert(depFin,dependentForm);
                forward = mapping.findForward(FORWARD_FINANCIALS_DEPENDENT_EDIT);
            }
		}
    	return forward;
    }
    
    /**
     * 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 update(ActionMapping mapping, 
                                ActionForm form,
                                HttpServletRequest request, 
                                HttpServletResponse response) throws Exception {
        
    	FinancialsDependentForm dependentForm = (FinancialsDependentForm)form;
    	boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
        dependentForm.setAddAPerson(isAddAPerson);
        
        // Get the income year from the cache and set it on the form
        Integer incomeYear = getSelectedIncomeYear(request);
        dependentForm.setIncomeYear(String.valueOf(incomeYear));

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

        if(incomeYear != null && StringUtils.isNotEmpty(dependentForm.getDependentId())) {
            if(dependentForm.getSpouseInd())  { 
                
                String spouseId = dependentForm.getDependentId();
                
                //More than one spouse is not allowed.
                SpouseFinancials activeSpouse = this.getActiveSpouse(incomeYear,person);
                EntityKey activeSpouseKey = (activeSpouse != null) ? activeSpouse.getEntityKey() : null;
                if(!dependentForm.isSpouseHasInactiveDate() && activeSpouseKey != null && !StringUtils.equals(spouseId,activeSpouseKey.getKeyValueAsString())) {
                    addActionMessageForField(request,SPOUSE_CANNOT_BE_ACTIVATED,SPOUSE_INACTIVE_DATE);
                    return mapping.findForward(FORWARD_FINANCIALS_SPOUSE_EDIT);
                }
                Person clonePerson = (Person)person.clone();
                SpouseFinancials spouseFinancials = (SpouseFinancials)getSpouseFinancialsById(clonePerson,dependentForm.getDependentId(),incomeYear);
                conversionService.convert(dependentForm,spouseFinancials);
                
               // CCR10471
            	if (isAddAPerson){
          			ActionForward overviewSuccessForward =
          				new ActionForward(mapping.findForward(FORWARD_FINANCIALS_SPOUSE_EDIT));
          			ActionForward samePageForward = mapping.findForward(FORWARD_FINANCIALS_SPOUSE_EDIT);
    	         
    	            // 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;
    	                }
    	            }
    	            Person updatedPerson = spouseFinancials.getPerson();
    	            updateSelectedPerson(request,updatedPerson);
            	}
            	else {
            		Person updatedPerson =  this.getFinancialsService().updateSpouseFinancials(incomeYear,spouseFinancials,clonePerson);
                    updateSelectedPerson(request,updatedPerson);	
            	}    
            } else {
                Person clonePerson = (Person)person.clone();
                DependentFinancials dependentFinancials = (DependentFinancials)getDependentFinancialsById(clonePerson, dependentForm.getDependentId(), incomeYear);
                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);
    }
    
    /**
     * Delete dependent.
     *
     * @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 delete(ActionMapping mapping, 
                                ActionForm form,
                                HttpServletRequest request, 
                                HttpServletResponse response) throws Exception {
        
    	FinancialsDependentForm dependentForm = getFinancialsDependentForm(form);
    	
        Integer incomeYear = getSelectedIncomeYear(request);
        dependentForm.setIncomeYear(String.valueOf(incomeYear));

    	String dependentId = dependentForm.getDependentId();
		if(StringUtils.isNotEmpty(dependentId))
		{
	   		// Get the Person object from the cache
	        Person person = getSelectedPerson(request);
            Person clonePerson = (Person)person.clone();
	        
	        deleteRelationFinancialsById(clonePerson, dependentId, incomeYear);
            Person updatedPerson =  this.getFinancialsService().updateDependents(incomeYear, clonePerson);
            updateSelectedPerson(request, updatedPerson);
        }
		
		return mapping.findForward(FORWARD_FINANCIALS_DEPENDENT_OVERVIEW);
    }

    protected void deleteRelationFinancialsById(Person person, String financialsId, Integer incomeYear) {

        FinancialStatement ftmt = person.getFinancialStatement(incomeYear);
        if(ftmt != null) {
            SpouseFinancials sf = this.getSpouseFinancialsById(person,financialsId,incomeYear);
            if(sf != null) {
                ftmt.removeSpouseFinancials(sf);
                return;
            }
            DependentFinancials df = this.getDependentFinancialsById(person,financialsId,incomeYear);
            if(df != null) {    
            	ftmt.removeDependentFinancials(df);
            }
        }
        return;
    }

    /**
     * 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);
    }

    /**
     * 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  {
        form.reset(mapping,request);
        return display(mapping,form,request,response);
    }
    
    /**
     * Initialize and get the Struts lookup dispatch method map hashmap.
     *
     * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
     * @return the method map
     */
   protected Map getKeyMethodMap()
    {
        Map map = new HashMap();
        map.put("button.update", "update");
        map.put("button.cancel", "cancel");
        map.put("button.delete", "delete");
        map.put("button.display", "display");
        return map;
    }
}