package gov.va.med.esr.ui.ee.action;

// Java classes
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Library classes
import org.apache.commons.lang.Validate;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

// Framework classes

// EDB Classes
import gov.va.med.esr.ui.common.action.PersonAbstractAction;
import gov.va.med.esr.ui.util.Financials1010EZApplication;
import gov.va.med.esr.ui.util.SessionManager;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.VOAApplication;

/**
 * The struts action for the enrollment screen.
 */
public class EnrollmentAction extends PersonAbstractAction
{
    // Struts Forwards
    public static final String CANCEL_FORWARD = "cancel";
    public static final String SUCCESS_FORWARD = "success";
    public static final String DISPLAY_FORWARD = "display";

    private String outputTempFilePath;

   	public String getOutputTempFilePath() {
   		return outputTempFilePath;
   	}

   	public void setOutputTempFilePath(String outputTempFilePath) {
   		this.outputTempFilePath = outputTempFilePath;
   	}

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

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet()
    {
        Validate.notNull(getPersonService(), "A person service is required");
        Validate.notNull(getEnrollmentService(), "An enrollment service is required");
    }

    /**
     * Handles the displaying of the enrollment 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
    {
        // Get a handle to the enrollment form
        EnrollmentForm enrollmentForm = (form instanceof EnrollmentForm) ? (EnrollmentForm)form : null;

        if (enrollmentForm != null) {
	        enrollmentForm.setAddAPerson(SessionManager.isAddAPerson(request));

	        // Get the Person object from the cache and set it on the form
	        Person person = getSelectedPerson(request);
	        enrollmentForm.setPerson(person);

	        // Convert all the person data to the form
	        conversionService.convert(person, enrollmentForm);
        }

        // Forward to the display
        return mapping.findForward(DISPLAY_FORWARD);
    }

    public ActionForward viewSubmissionData(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {

    	// return mapping.findForward(FORWARD_FINANCIALS_1010EZ);
    	 // Get person
         Person person = getSelectedPerson(request);

         //get most recent app
         VOAApplication onlineApp = this.getVoaApplicationService().findMostRecentApplicationBySSN
        		 (person.getIdentityTraits().getSsnText());

         if (onlineApp == null) {
        	 this.addActionMessage(request, new ActionMessage("message.noApplicationData"));
        	 return mapping.findForward(DISPLAY_FORWARD);

         }

         InputStream isTemp = this.getClass().getResourceAsStream("/Fillable20151010EZHealthcareApplication.pdf");
   		 if (isTemp == null)
   			 log.info("The 1010EZ template form resource could not be found!");


         String tempoutFilePath = this.getOutputTempFilePath();
         Financials1010EZApplication onlineSubmissionForm = new Financials1010EZApplication(person, onlineApp, isTemp, tempoutFilePath) ;
         onlineSubmissionForm.getOnline1010EZ();
         onlineSubmissionForm.display1010EZ(response);
   		 return null;
   }

    /**
     * Handles the update processing.
     *
     * @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
    {
        // Get a handle to the enrollment form
        EnrollmentForm enrollmentForm = (form instanceof EnrollmentForm) ? (EnrollmentForm)form : null;

        boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
        if (enrollmentForm != null) {
	        enrollmentForm.setAddAPerson(isAddAPerson);

	        // Clone the person to make updates
	        Person person = getSelectedPerson(request);
	        Person updatePerson = (Person)person.clone();

	        // Convert the form data onto the updated Person object
	        conversionService.convert(enrollmentForm, updatePerson);


	        if (!isAddAPerson){
	        // Call service layer to perform the update
	        	updatePerson = getEnrollmentService().updateEnrollmentData(updatePerson);
	        }
	        // Store updated person in the cache
	        updateSelectedPerson(request, updatePerson);
        }
        // Return to the overview screen
        return mapping.findForward(SUCCESS_FORWARD);
    }

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

    /**
     * Handles the cancel processing.
     *
     * @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 to the overview screen
        return mapping.findForward(CANCEL_FORWARD);
    }

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