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

// Java classes
import gov.va.med.esr.common.model.insurance.InsurancePolicy;
import gov.va.med.esr.common.model.insurance.PrivateInsurance;
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.esr.ui.common.util.DateUtils;
import gov.va.med.esr.ui.util.SessionManager;
import gov.va.med.fw.validation.ValidationMessages;

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;

/**
 * @author DNS   RAMACP
 *         <p/>
 *         TODO To change the template for this generated type comment go to Window - Preferences -
 *         Java - Code Style - Code Templates
 */
public class InsuranceAddAction extends InsuranceInfoAction
{
    public InsuranceAddAction()
    {
        super();
    }

    //called when validation fails
    public ActionForward display(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception
    {
        return mapping.findForward("success");
    }

    public ActionForward add(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception
    {
        InsuranceInfoForm insForm =
            (form instanceof InsuranceInfoForm) ? (InsuranceInfoForm)form : null;

         ActionForward samePageForward = mapping.findForward(FORWARD_RETURN_TO_SAME_PAGE);
         
         if (insForm == null) {
        	 return samePageForward;
         }
         
         boolean isAddAPerson = false;
         isAddAPerson = SessionManager.isAddAPerson(request);
         insForm.setAddAPerson(isAddAPerson);
         
        // Get the Person object from the cache
        Person person = getSelectedPerson(request);

        // Create some action forwards
        ActionForward overviewSuccessForward =
            new ActionForward(mapping.findForward(FORWARD_TO_OVERVIEW_PAGE));
        

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

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

        InsurancePolicy policy;
        // Medicare creation and update is handled in InsuranceEdit Action
        policy = new PrivateInsurance();

        conversionService.convert(insForm, policy);

        Person updatedPerson = (Person)person.clone();
        updatedPerson.addInsurance(policy);

        ValidationMessages messages = new ValidationMessages();
        // Call service layer here
        if (isAddAPerson){
        	// if (policy!=null){
        	// 	updatedPerson =  policy.getPerson();
        	// }
        	updateSelectedPerson(request, updatedPerson);
        }
        else{
        	messages = getInsuranceService().updateInsurance(updatedPerson);

        	// Store updated person in the cache
        	updateSelectedPerson(request, updatedPerson);
        }
        ActionForward successForward = getForwardPathFromValidationMessages(mapping, messages,
                FORWARD_TO_OVERVIEW_PAGE);

        return successForward;

    }

    public ActionForward cancel(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception
    {
        return mapping.findForward("cancel");
    }

    public ActionForward addPrivateIns(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception
    {
        Person person = getSelectedPerson(request);
        InsuranceInfoForm insForm =
            (form instanceof InsuranceInfoForm) ? (InsuranceInfoForm)form : null;
        
        if (insForm != null) {
	        insForm.setMedicareInd(false);
	        boolean isAddAPerson = false;
	        isAddAPerson = SessionManager.isAddAPerson(request);
	        insForm.setAddAPerson(isAddAPerson);
	        
	        if(person.getDeathRecord() !=null && person.getDeathRecord().getDeathDate()!=null){
	            String dod=DateUtils.format(person.getDeathRecord().getDeathDate(), null);
	            insForm.setDateOfDeath(dod);
	        }
	        if(person.getBirthRecord() !=null && person.getBirthRecord().getBirthDate()!=null){
	              String dob=DateUtils.format(person.getBirthRecord().getBirthDate(), null);
	              insForm.setDateOfBirth(dob);
	        }
        }
        return mapping.findForward("success");
    }

    public ActionForward addMedicare(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception
    {
        Person person = getSelectedPerson(request);
        InsuranceInfoForm insForm =
            (form instanceof InsuranceInfoForm) ? (InsuranceInfoForm)form : null;
            
        if (insForm != null) {
	        insForm.setMedicareInd(true);  
	        insForm.setInsCompanyName("Medicare");
	        boolean isAddAPerson = false;
	        isAddAPerson = SessionManager.isAddAPerson(request);
	        insForm.setAddAPerson(isAddAPerson);
	        
	        if(person.getBirthRecord() !=null && person.getBirthRecord().getBirthDate()!=null){
	            String dob=DateUtils.format(person.getBirthRecord().getBirthDate(), null);
	            insForm.setDateOfBirth(dob);
	        }
	        //ccr 10116 Medicare Insurance (Part a & Part B) Effective Date cannot be after DOD
	        if(person.getDeathRecord() !=null && person.getDeathRecord().getDeathDate()!=null){
	            String dod=DateUtils.format(person.getDeathRecord().getDeathDate(), null);
	            insForm.setDateOfDeath(dod);
	        }
        }
        return mapping.findForward("addMedicare");
    }


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

}

