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

// Java Classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

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

// ESR Classes
import gov.va.med.esr.common.model.SiteYear;
import gov.va.med.esr.common.model.ee.FeeBasis;
import gov.va.med.esr.common.model.financials.IncomeTest;
import gov.va.med.esr.common.model.financials.PatientVisitSummary;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.ui.common.action.PersonAbstractAction;
import gov.va.med.esr.ui.facility.beans.FacilityBean;
import gov.va.med.esr.ui.facility.beans.FeeBasisProgramBean;
import gov.va.med.esr.ui.message.action.MessageConstants;
import gov.va.med.esr.ui.message.action.MessageSearchForm;
import gov.va.med.esr.ui.util.SessionManager;

/**
 * @author Madhu Katikala, Muddaiah Ranga
 */
public class FacilityAction extends PersonAbstractAction implements FacilityConstants {
   /**
    * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
    */
   public void afterPropertiesSet() {
   	// Check for required fields here
   }     

   public ActionForward display(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        //get the selected person from the session 
        Person person = getSelectedPerson( request );
                
        List facilities = convert(person);
        
        if (facilities != null && facilities.size() > 0) {
        	
            request.setAttribute(FACILITYS,facilities);
            
            // Get the value list information
            ValueList valueList = ValueListActionUtils.getValueList(form, request,FACILITY_TABLE_ID,FACILITY_VALUE_LIST_ADAPTER,facilities);
            
            // Backup the ValueListInfo into session and store the resultant ValueList on the request
            ValueListActionUtils.setValueList(request, valueList,MessageConstants.VALUE_LIST);
        }
        
        // Get a handle to the enrollment form
        MessageSearchForm facilityForm = (form instanceof MessageSearchForm) ? (MessageSearchForm)form : null;
        
        boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
        if (facilityForm != null) {
        	facilityForm.setAddAPerson(isAddAPerson);    
        }

        //end of test code
        return mapping.findForward(SUCCESS);
    }
    
    /**
     * 
     * @param person
     * @return
     */
    private List convert(Person person) {
    	
    	Map facilities = new HashMap ();
    	
        //retrieve patient visit summaries and populate the list
        Map patientVisits = person.getPatientVisitSummaries();
            	        
        VAFacility preferredFacility = person.getMostRecentPreferredFacility();
        
        if (preferredFacility != null) {
    		FacilityBean facilityBean = new FacilityBean (preferredFacility);
    		facilityBean.setPreferredFacility(Boolean.TRUE);
        	facilities.put(preferredFacility,facilityBean);
        }
        
        IncomeTest incomeTest = getPersonHelperService().getCurrentIncomeTest(person);
        
        VAFacility siteConductingTest = null;
        if (incomeTest != null) {
        	siteConductingTest = incomeTest.getSiteConductingTest();
            if (siteConductingTest != null) {
        		FacilityBean facilityBean = (FacilityBean) facilities.get(siteConductingTest);
        		if (facilityBean == null)	
        			facilityBean = new FacilityBean (siteConductingTest);
        		
        		facilityBean.setPrimaryTestFacility(Boolean.TRUE);
            	facilities.put(siteConductingTest,facilityBean);
            }
        }
        
        //Convert Fee Basis Information
        Set feeBasisSet = person.getFeeBasis();

        //Add Fee basis information to the facilities
        if (feeBasisSet != null && feeBasisSet.size() > 0) {
        	for (Iterator iter=feeBasisSet.iterator(); iter.hasNext();) {
        		FeeBasis feeBasis = (FeeBasis) iter.next();
                VAFacility reportSite = (feeBasis != null) ? feeBasis.getReportSite() : null;
        		if(reportSite != null) {
                    FacilityBean facilityBean = (FacilityBean)facilities.get(reportSite);
                    if (facilityBean == null) {
                        facilityBean = new FacilityBean(reportSite);
                        facilities.put(reportSite,facilityBean);
                    }
                    FeeBasisProgramBean feeBasisBean= new FeeBasisProgramBean ();
                    feeBasisBean.setName((feeBasis.getProgram()!=null)?feeBasis.getProgram().getDescription():null);
                    feeBasisBean.setTreatmentType((feeBasis.getTreatmentType() !=null)?feeBasis.getTreatmentType().getDescription():null);
                    feeBasisBean.setAuthorizationFrom(feeBasis.getAuthorizationFromDate());
                    feeBasisBean.setAuthorizationTo(feeBasis.getAuthorizationToDate());
                    feeBasisBean.setReportDate(feeBasis.getReportDate());
                    facilityBean.addFeeBasis(feeBasisBean);
                }
        	}
        }
            	
    	//convert the data to beans
    	Set facilityKeys = patientVisits.keySet();

    	for (Iterator iter=facilityKeys.iterator(); iter.hasNext();) {
    		SiteYear siteYear = (SiteYear) iter.next ();
            if(siteYear != null) {
                PatientVisitSummary patientVisitSummary = (PatientVisitSummary)patientVisits.get(siteYear);
                VAFacility facility = siteYear.getFacility();   	
    		
                //create a new Bean if not already created and set data
                FacilityBean facilityBean = (FacilityBean) facilities.get(facility);    		
                if (facilityBean== null)
                    facilityBean = new FacilityBean (facility);
                facilities.put(facility,facilityBean);
   		   		
                facilityBean.addPatientVisitSummary(patientVisitSummary);
            }
    	}

    	List sortedList = new ArrayList (facilities.values());
    	Collections.sort(sortedList); //customr sorting based on priority and visit dates
    	return sortedList;
    }    
}
