/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.ui.demographic.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.ui.ApplicationConstants.MessageKeys;
import gov.va.med.esr.ui.common.action.AddressForm;
import gov.va.med.esr.ui.common.action.AddressValidationAction;
import gov.va.med.esr.ui.util.SessionManager;
import gov.va.med.fw.service.ServiceConfigurationException;
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;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;

/**
 * This struts action is used to support the demographics personal page.
 *
 * @author Andrew Pach
 * @version 3.0
 */
// public class DemographicPersonalAction extends PersonAbstractAction
public class DemographicPersonalAction extends AddressValidationAction
{
    // Struts forwards
    public static final String FORWARD_DEMOGRAPHIC_PERSONAL = "demographicPersonal";
    public static final String FORWARD_DEMOGRAPHIC_OVERVIEW = "demographicOverview";
    public static final String FORWARD_DEMOGRAPHIC_PERSONAL_HISTORY = "demographicPersonalHistory";
    public static final String FORWARD_CANCEL = "cancel";
    public static final String FORWARD_508_NOTES = "personal508Notes";
    public static final String FORWARD_RETURN_TO_SAME_PAGE = "success";

    /**
     * Default constructor.
     */
    public DemographicPersonalAction()
    {
        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
    {
    	   boolean isAddAPerson = false;
           isAddAPerson = SessionManager.isAddAPerson(request);
           DemographicPersonalForm personalForm = getPersonalForm(form);
           personalForm.setAddAPerson(isAddAPerson);
       // conversionService.convert(getSelectedPerson(request),getPersonalForm(form));
        conversionService.convert(getSelectedPerson(request),personalForm);
        return mapping.findForward(FORWARD_DEMOGRAPHIC_PERSONAL);
    }

    /**
     * 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
    {
    	 boolean isAddAPerson = false;
         isAddAPerson = SessionManager.isAddAPerson(request);

         DemographicPersonalForm personalForm =
             (form instanceof DemographicPersonalForm) ? (DemographicPersonalForm)form : null;
         personalForm.setAddAPerson(isAddAPerson);

         MessageResources messageResources = personalForm.getResources(request);
         ActionMessages errors = personalForm.getActionMessages(request);

         if (isAddAPerson){
        	 ActionForward overviewSuccessForward =
                 new ActionForward(mapping.findForward(FORWARD_DEMOGRAPHIC_OVERVIEW));
             ActionForward samePageForward = mapping.findForward(FORWARD_DEMOGRAPHIC_PERSONAL);

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

                 // Validate the zip code matches the city/state
                 if (!zipCodeMatchesCityAndState(personalForm, AddressForm.class, CITY_FIELD, STATE_FIELD,
                     ZIPCODE_FIELD, request))
                 {
                     return samePageForward;
                 }
             }
             boolean requiredFieldNotEntered = false;
         	// validate required fields preferred facility, marital status
         	/* CCR10640 -- allow multiple preferred facilities.
         	 if (personalForm.getPreferredFacility()== null || StringUtils.isEmpty(personalForm.getPreferredFacility())){
         		requiredFieldNotEntered = true;
         		errors.add("PreferredFacility", new ActionMessage(MessageKeys.ERRORS_REQUIRED, "Preferred Facility"));
         	} */

         	if (personalForm.getPreferredFacilitySites() == null ||
         		personalForm.getPreferredFacilitySites().isEmpty() ||
         		StringUtils.isEmpty((String)personalForm.getPreferredFacilitySites().get(0))) {
         		requiredFieldNotEntered = true;
         		errors.add("PreferredFacility", new ActionMessage(MessageKeys.ERRORS_REQUIRED, "Preferred Facility"));
         	}

         	if (personalForm.getMaritalStatus()== null || StringUtils.isEmpty(personalForm.getMaritalStatus())){
         		requiredFieldNotEntered = true;
        		 	errors.add("MaritalStatus", new ActionMessage(MessageKeys.ERRORS_REQUIRED, "Marital Status"));
         	}


         	if (personalForm.getAppointmentRequestResponse()== null || StringUtils.isEmpty(personalForm.getAppointmentRequestResponse())){
         		requiredFieldNotEntered = true;
        		 	errors.add("appointmentRequestResponse", new ActionMessage(MessageKeys.ERRORS_REQUIRED, "Appointment Request Response"));
         	}

            if (StringUtils.isEmpty(personalForm.getPreferredLanguageCode())){
                requiredFieldNotEntered = true;
                    errors.add("PreferredLanguage", new ActionMessage(MessageKeys.ERRORS_REQUIRED, "Preferred Language"));
            }

            if (StringUtils.isEmpty(personalForm.getLanguageEntryDate())){
                requiredFieldNotEntered = true;
                    errors.add("LanguageEntryDate", new ActionMessage(MessageKeys.ERRORS_REQUIRED, "Language Entry Date"));
            }

         	if (requiredFieldNotEntered)
         		return samePageForward;

             //clone the person
           Person updatedPerson = (Person)getSelectedPerson(request).clone();
             //convert from to Person
           conversionService.convert(getPersonalForm(form),updatedPerson);

           //save the person back to session
           updateSelectedPerson(request,updatedPerson);
           return mapping.findForward(FORWARD_DEMOGRAPHIC_OVERVIEW);
        }

        //clone the person
        Person updatedPerson = (Person)getSelectedPerson(request).clone();

        //convert from to Person
        conversionService.convert(getPersonalForm(form),updatedPerson);

        //Call business services to validate and update
        updatedPerson = getDemographicService().updateDemographicInformation(updatedPerson);

        //save the person back to session
        updateSelectedPerson(request,updatedPerson, true);

        return mapping.findForward(FORWARD_DEMOGRAPHIC_OVERVIEW);
    }

    protected ActionForward handleOptimisticLockException(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) throws Exception
    {
    	form.reset(mapping,request);
    	return display(mapping,form,request,response);
    }
    /**
     * 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_CANCEL);
    }

    /**
     * Cancels this page and goes to the view personal history 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 gotoHistory(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        return mapping.findForward(FORWARD_DEMOGRAPHIC_PERSONAL_HISTORY);
    }

    /**
     * Cancels this page and goes to the view 508 notes 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 goto508Notes(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        return mapping.findForward(FORWARD_508_NOTES);
    }

    /**
     * Checks to ensure the passed in ActionForm is not null and of the correct type.
     *
     * @param form The struts form to check
     * @return The passed in form type-casted to a DemographicPersonalForm
     * @throws gov.va.med.fw.service.ServiceConfigurationException if the form is null or of an incorrect type.
     */
    protected DemographicPersonalForm getPersonalForm(ActionForm form) throws ServiceConfigurationException
    {
        DemographicPersonalForm personalForm =
            (form instanceof DemographicPersonalForm) ? (DemographicPersonalForm)form : null;
        if (personalForm == null)
        {
            throw new ServiceConfigurationException("DemographicPersonalForm not properly configured.");
        }
        return personalForm;
    }

    /**
     * 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.continue", "update");
        map.put("button.viewHistoricalPersonalData", "gotoHistory");
        map.put("button.viewPersonal508Notes", "goto508Notes");
        map.put("text.subMenu.personal", "display");
        return map;
    }

	/**
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() {
		// Checked for required components here
	}
}