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

// Java classes
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

// Library classes
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;
import net.mlw.vlh.ValueList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//Framework classes
import gov.va.med.fw.ui.struts.ValueListActionUtils;

// ESR Classes
import gov.va.med.esr.common.model.financials.IncomeTest;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.VOAApplication;
import gov.va.med.esr.ui.common.util.DateUtils;
import gov.va.med.esr.ui.util.Financials1010EZApplication;
import gov.va.med.esr.ui.util.Financials1010EZRRenewal;
/**
 * Struts action class that will handle the Financials Overview screen.
 *
 * @author Priya Ramachandran
 * @author Andrew Pach
 * @version: 3.0
 */
public class FinancialsOverviewAction extends FinancialsAction
{
    /* The Valid Income Year list session key */
    public static final String VALID_INCOME_YEAR_LIST_SESSION_KEY = "validIncomeYearListSessionKey";
  //   public static final String FORWARD_FINANCIALS_1010EZ = "financialsHealthBenefitApplication";
  //   public static final String FORWARD_FINANCIALS_1010EZR = "financialsHealthBenefitRenewal";
  //  private static final String fillable1010EZRFileName = "Fillable1010EZRHealthcareApplication.pdf";
  //   private static final String fillable1010EZFileName  = "Fillable1010EZHealthcareApplication.pdf";
    private String outputTempFilePath;

	public String getOutputTempFilePath() {
		return outputTempFilePath;
	}

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

	public FinancialsOverviewAction()
    {
        super();
    }

    /**
     * Displays the financials overview page.  If no income year had been previously selected and set into
     * the session, this method will determine and set the income year appropriately.  Otherwise, the currently
     * selected income year will be used.
     *
     * @param mapping An action mapping
     * @param form A form bean
     * @param request A http request from an search.jsp page
     * @param response A http response to stream data to a next page
     *
     * @return An action forward class encapsulating information about a next page
     * @throws Exception Thrown if failed to process
     */
    public ActionForward display(ActionMapping mapping, ActionForm form,
             HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        // Get the financials form
        FinancialsForm finForm = getFinancialsForm(form);


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

        // Get the currently selected income year
        Integer incomeYear = getSelectedIncomeYear(request);
        IncomeTest selectedIncomeTest = null;
        IncomeTest currentIncomeTest = null;

        // If an income year wasn't previously selected, determine what the income year should be and
        // initialize the valid income years in the session (first time this screen has been visited
        // for the currently selected veteran).
        // Otherwise, use the previously selected income year (this screen has been visited previously).

        //Added below to fix ESR 4.0_CodeCR13520
        //Initialize details that can be use to determine selected IY is valid
        Integer expectedIncomeYear = null;
        // Initialize the valid income years for this veteran into the session
        List validIncomeYears = initializeValidIncomeYears(request, person);

        // Get the current income test and use it's year as the initial selection
        selectedIncomeTest = getPersonHelperService().getCurrentIncomeTest(person);
        if (selectedIncomeTest != null)
        {
        	expectedIncomeYear = selectedIncomeTest.getIncomeYear();
            //currentIncomeTest = selectedIncomeTest;
        }
        else
        {
            // If there is no current income test, try to get the latest income test defined
            selectedIncomeTest = getPersonHelperService().getLatestIncomeTest(person);
            if (selectedIncomeTest != null)
            {
            	expectedIncomeYear = selectedIncomeTest.getIncomeYear();
            }
            else
            {
                // If no income tests are defined for this veteran, use the current year
            	expectedIncomeYear = new Integer(DateUtils.getCurrentYear()-1);
            }
        }

        if (incomeYear == null)
        {
        	//Set expected valid IY as selected IY
    		incomeYear = expectedIncomeYear;

        	if (selectedIncomeTest != null) {
        		currentIncomeTest = selectedIncomeTest;
        	}
        }
        else
        {
        	//Added below to fix ESR 4.0_CodeCR13520
        	boolean isGivenIYValid = isGivenIYValid(validIncomeYears, incomeYear);

        	if (!isGivenIYValid) {
        		//Set valid IY as selected IY
        		incomeYear = expectedIncomeYear;
        	}

            // Get the income test for the selected year
            selectedIncomeTest = person.getIncomeTest(incomeYear);
        }

        // If we haven't yet retrieved the current income test, get it now
        if (currentIncomeTest == null)
        {
            // Get the current income test and use it's year as the initial selection
            currentIncomeTest = getPersonHelperService().getCurrentIncomeTest(person);
        }

        // Set whether the selected income test is current
        if ((currentIncomeTest != null) && (selectedIncomeTest != null) &&
            (currentIncomeTest.getIncomeYear().equals(selectedIncomeTest.getIncomeYear())))
        {
            finForm.setIsCurrentIncomeTest(true);
        }
        else
        {
            finForm.setIsCurrentIncomeTest(false);
        }

        // Set the currently selected income year in the session and on the form
        setSelectedIncomeYear(request, incomeYear);
        finForm.setIncomeYear(String.valueOf(incomeYear));

        // Set the income test on the form (even if it is null)
        finForm.setIncometest(selectedIncomeTest);

        if (selectedIncomeTest != null)
        	finForm.setBtFinancialInd(selectedIncomeTest.getBtFinancialInd());


        // Determine if the data associated with the currently selected income year can be edited
        finForm.setCanFinancialsBeAdded(getFinancialsService().canFinancialsBeUpdated(incomeYear, person));

        // Convert data from the person onto the form
        conversionService.convert(person, finForm);

/*      <vlh:root id="dependentTableId" value="vlDepend"
 * 		<vlh:root id="incomeTableId" value="vlIncome"
 * 		<vlh:root id="expenseTableId" value="vlExpense"
 * 		<vlh:root id="assetTableId" value="vlAsset"
 * 		<vlh:root id="debtTableId" value="vlDebt"
 * 		<vlh:root id="benTravelTableId" value="vlBenTravel"
 */

        // Set the spouse and dependent data into a valuelist
        ValueList valueList1 = ValueListActionUtils.getValueList(finForm,
            request, "dependentTableId", "financialDependentAdapter", finForm.getDependentInfoList());
        // Backup the ValueListInfo into session and store the resultant ValueList on the request
        ValueListActionUtils.setValueList(request, valueList1, "vlDepend");

        // Set the income data into a valuelist
        ValueList valueList2 = ValueListActionUtils.getValueList(finForm,
            request, "incomeTableId", "financialDependentAdapter", finForm.getIncomes());
        // Backup the ValueListInfo into session and store the resultant ValueList on the request
        ValueListActionUtils.setValueList(request, valueList2, "vlIncome");

        // Set the expense data into a valuelist
        ValueList valueList3 = ValueListActionUtils.getValueList(finForm,
            request, "expenseTableId", "financialDependentAdapter", finForm.getExpenses());
        // Backup the ValueListInfo into session and store the resultant ValueList on the request
        ValueListActionUtils.setValueList(request, valueList3, "vlExpense");

        // Set the asset data into a valuelist
        ValueList valueList4 = ValueListActionUtils.getValueList(finForm,
            request, "assetTableId", "financialDependentAdapter", finForm.getAssets());
        // Backup the ValueListInfo into session and store the resultant ValueList on the request
        ValueListActionUtils.setValueList(request, valueList4, "vlAsset");

        // Set the debt data into a valuelist
        ValueList valueList5 = ValueListActionUtils.getValueList(finForm,
            request, "debtTableId", "financialDependentAdapter", finForm.getDebts());
        // Backup the ValueListInfo into session and store the resultant ValueList on the request
        ValueListActionUtils.setValueList(request, valueList5, "vlDebt");

        // Set the spouse and dependent data into a valuelist
        //since beneficiary is a collection, need to convert it to list
        ArrayList benTravelLst = new ArrayList();
        if (finForm.getBeneficiaryTravels() != null) {
        	for (Iterator it = finForm.getBeneficiaryTravels().iterator(); it.hasNext(); ) {
        		benTravelLst.add(it.next());
        	}
        }
        ValueList valueList6 = ValueListActionUtils.getValueList(finForm,
            request, "benTravelTableId", "financialDependentAdapter", benTravelLst);
        // Backup the ValueListInfo into session and store the resultant ValueList on the request
        ValueListActionUtils.setValueList(request, valueList6, "vlBenTravel");


//      Go to the financials overview page
        return mapping.findForward(FORWARD_FINANCIALS_OVERVIEW);
    }

    /**
     * Handles when the user selects a specific financial year to view.
     *
     * @param mapping An action mapping
     * @param form A form bean
     * @param request A http request from an search.jsp page
     * @param response A http response to stream data to a next page
     *
     * @return An action forward class encapsulating information about a next page
     * @throws Exception Thrown if failed to process
     */
    public ActionForward viewData(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        // Get the financials form
        FinancialsForm finForm = getFinancialsForm(form);


        // Set the newly selected income year
        Integer incomeYear = new Integer(finForm.getIncomeYear());
        setSelectedIncomeYear(request, incomeYear);
        // Set focus button
        finForm.setFocusButton("viewData");



        // Call display to get the income test and convert the data to the form for the newly selected year
        return display(mapping, form, request, response);

    }

    public ActionForward print1010EZ(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
    	// return mapping.findForward(FORWARD_FINANCIALS_1010EZ);
    	 // Get person
         Person person = getSelectedPerson(request);
         // Get the currently selected income year

         // Set the newly selected income year
         FinancialsForm finForm = getFinancialsForm(form);
         Integer incomeYear = new Integer(finForm.getIncomeYear());
         setSelectedIncomeYear(request, incomeYear);
         // Get the currently selected income year
         // Integer incomeYear = getSelectedIncomeYear(request);

         // WebApplicationContext ac = DelegatingActionUtils.findRequiredWebApplicationContext( request.getSession().getServletContext() );
         // String filePath = ac.getServletContext().getRealPath("/");
         // String templateFilePath = request.getSession().getServletContext().getRealPath("/");
         InputStream isTemp = this.getClass().getResourceAsStream("/Fillable1010EZHealthcareApplication.pdf");
   		 if (isTemp == null)
   			 log.info("The 1010EZ template form resource could not be found!");

         String tempoutFilePath = this.getOutputTempFilePath();
      //   Financials1010EZApplication printform1010EZ = new Financials1010EZApplication(person, incomeYear, templateFilePath, tempoutFilePath) ;
         Financials1010EZApplication printform1010EZ = new Financials1010EZApplication(person, incomeYear, isTemp, tempoutFilePath) ;
   	     printform1010EZ.get1010EZ();
   	     printform1010EZ.display1010EZ(response);
   		 return null;
   }

    public ActionForward print1010EZR(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
        {
    		 // return mapping.findForward(FORWARD_FINANCIALS_1010EZR);
    	  	 // Get person
             Person person = getSelectedPerson(request);

             // Set the newly selected income year
             FinancialsForm finForm = getFinancialsForm(form);
             Integer incomeYear = new Integer(finForm.getIncomeYear());
             setSelectedIncomeYear(request, incomeYear);

             // Get the currently selected income year
             // Integer incomeYear = getSelectedIncomeYear(request);

             //	String templateFilePath = request.getSession().getServletContext().getRealPath("/");
       		 InputStream isTemp = this.getClass().getResourceAsStream("/Fillable1010EZRHealthcareApplication.pdf");
       		 if (isTemp == null)
       			 log.info("The 1010EZR form template resource could not be found!");

       		 String tempoutFilePath = this.getOutputTempFilePath();
       		 // Financials1010EZRRenewal printform1010EZR = new Financials1010EZRRenewal(person, incomeYear, templateFilePath, tempoutFilePath) ;
       		 Financials1010EZRRenewal printform1010EZR = new Financials1010EZRRenewal(person, incomeYear, isTemp, tempoutFilePath) ;
      	     printform1010EZR.get1010EZR();
      	     printform1010EZR.display1010EZR(response);
       		 return null;
   }

    /**
     * Initializes the list of valid income years for this veteran in the session.
     *
     * @param request The HttpServletRequest
     * @param person The person
     */
    protected List initializeValidIncomeYears(HttpServletRequest request, Person person)
    {
        // Get the list of LabelValueBeans if they were previous stored in the session
        List incomeYearBeans = new ArrayList();

        // Get the list of valid income years
        List incomeYears = determineValidIncomeYears(person);

        // Iterate through each valid year and create/add a LabelValueBean to the incomeYearBean list
        for (Iterator iterator = incomeYears.iterator(); iterator.hasNext();)
        {
            String year = String.valueOf(((Integer)iterator.next()).intValue());
            incomeYearBeans.add(new LabelValueBean(year, year));
        }

        // Store the list of years (as LabelValueBeans) in the session
        request.getSession().setAttribute(VALID_INCOME_YEAR_LIST_SESSION_KEY, incomeYearBeans);
        return incomeYears;
    }

    protected boolean isGivenIYValid(List incomeYears, Integer incomeYear) {
    	boolean isGivenIYValid = false;

    	if (incomeYear != null && incomeYears != null && incomeYears.size() > 0) {
	        // Iterate through each valid year and verify if given IY is within list
	        for (Iterator iterator = incomeYears.iterator(); iterator.hasNext();)
	        {
	            int year = ((Integer)iterator.next()).intValue();
	            if (year == incomeYear) {
	            	isGivenIYValid = true;
	            	break;
	            }
	        }
    	}
    	return isGivenIYValid;
    }

    /**
     * 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("title.financials", "display");
        map.put("button.viewData", "viewData");
        map.put("button.print1010EZ", "print1010EZ");
        map.put("button.print1010EZR", "print1010EZR");
        return map;
    }

}