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

// Java classes
import gov.va.med.esr.common.model.lookup.NameType;
import gov.va.med.esr.common.model.person.Name;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.ui.form.FinancialDetailsForm;
import gov.va.med.esr.ui.demographic.action.DemographicIdentityTraitsForm;
import gov.va.med.esr.ui.util.SessionManager;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

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 add page.
 *
 * @author Priya R.
 * @version 3.0
 */
public class FinancialDetailsAddAction extends FinancialsAction
{
    // Struts forwards
    public static final String FORWARD_FINANCIAL_DETAILS_ADD = "financialDetailsAdd";

    /**
     * Default constructor.
     */
    public FinancialDetailsAddAction()
    {
        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
    {
        FinancialDetailsForm detailsForm = getFinancialDetailsForm(form);
        
        boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
        detailsForm.setAddAPerson(isAddAPerson);
        
        //set the indicator for new record
        detailsForm.setNewIncomeTestInd(true);
                
		// 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);
        detailsForm.setIncomeYear(String.valueOf(incomeYear));
        
        //create new income test and add to person
        //IncomeTest test = new IncomeTest();
        //test.setIncomeYear(incomeYear);
        //person.setIncomeTest(incomeYear, test);
  
        //get person display name
        getPersonName(person, detailsForm);

        //get spouse and dependent info
        //getDependentList(person, detailsForm);
		
        return mapping.findForward(FORWARD_FINANCIAL_DETAILS_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
    {
    	form.reset(mapping,request);
    	return display(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
    {

		FinancialDetailsForm detailsForm = getFinancialDetailsForm(form);
		 boolean isAddAPerson = false;
	     isAddAPerson = SessionManager.isAddAPerson(request);
	     detailsForm.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);
        detailsForm.setIncomeYear(String.valueOf(incomeYear));
        
		if(conversionService != null)
		{
			Person clonePerson = (Person)person.clone();
			
			conversionService.convert(detailsForm,clonePerson);

			// Call service layer here
	        if (isAddAPerson){
	        	updateSelectedPerson( request, clonePerson );
	        }
	        else {
	        	Person updatedPerson = invokeUpdateFinancialAssessment(detailsForm, incomeYear, clonePerson);	
	        	// Store updated person in the cache
	        	updateSelectedPerson( request, updatedPerson );
	        }
		}

		return mapping.findForward(FORWARD_FINANCIALS_SUMMARY);
    }



    /**
     * Review the impact to finacial 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 reviewImpact(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {

		FinancialDetailsForm detailsForm = getFinancialDetailsForm(form);
		boolean isAddAPerson = false;
	    isAddAPerson = SessionManager.isAddAPerson(request);
	    detailsForm.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);
        detailsForm.setIncomeYear(String.valueOf(incomeYear));

        
		if(conversionService != null)
		{
			Person clonePerson = (Person)person.clone();
			
			conversionService.convert(detailsForm,clonePerson);
			
		    // Store updated person in the cache
			setUpdatedPerson( request, clonePerson );
	
		    // Call service layer here
		    if (!isAddAPerson){
		    	Person calPerson = invokeAssessReviewImpact(detailsForm, incomeYear, clonePerson);
				
		    	// Store calculated person in the cache
		    	if(calPerson != null)
		    		SessionManager.setCalculatedPerson( request, calPerson );
		    }
		}
		return mapping.findForward(FORWARD_FINANCIAL_REVIEW_IMPACT_DISPLAY);
    } 
    
    /**
     * 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_SUMMARY);
    }

    /**
     * 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.addIncomeTest", "display");
			keyMethodMap.put("button.addTest", "add");
			keyMethodMap.put("button.cancel", "cancel");
			keyMethodMap.put("button.reviewImpact", "reviewImpact");
			keyMethodMap.put("button.display","display");
		}
	    return keyMethodMap;
    }
        
    private void getPersonName(Person person, FinancialDetailsForm form)
    {
	   	Set otherNames = new HashSet(person.getNames());
		Name name = Name.getNameOfType(otherNames,NameType.LEGAL_NAME.getName());
		
		if (name != null) 
		{
			StringBuffer displayName = new StringBuffer(name.getGivenName());
			
			displayName.append(" ");
			displayName.append(name.getFamilyName());
			//displayName.append(" (Veteran)");
			form.setName(displayName.toString());
		}
    }
}