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

// Java imports
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;



// ESR imports
import gov.va.med.esr.common.infra.ImpreciseDate;
import gov.va.med.esr.common.model.lookup.AACIndicator;
import gov.va.med.esr.common.model.lookup.AckType;
import gov.va.med.esr.common.model.lookup.BadAddressReason;
import gov.va.med.esr.common.model.lookup.CancelDeclineReason;
import gov.va.med.esr.common.model.lookup.ComAACErrorType;
import gov.va.med.esr.common.model.lookup.ComAACRejectReasonType;
import gov.va.med.esr.common.model.lookup.DayOfMonth;
import gov.va.med.esr.common.model.lookup.DayOfQuarter;
import gov.va.med.esr.common.model.lookup.DayOfWeek;
import gov.va.med.esr.common.model.lookup.EnrollmentOverrideReason;
import gov.va.med.esr.common.model.lookup.EnrollmentPriorityGroup;
import gov.va.med.esr.common.model.lookup.EnrollmentPrioritySubGroup;
import gov.va.med.esr.common.model.lookup.EnrollmentProcessStatus;
import gov.va.med.esr.common.model.lookup.EnrollmentStatus;
import gov.va.med.esr.common.model.lookup.EnrollmentStatusComponent;
import gov.va.med.esr.common.model.lookup.FunctionalGroup;
import gov.va.med.esr.common.model.lookup.MessageType;
import gov.va.med.esr.common.model.lookup.Month;
import gov.va.med.esr.common.model.lookup.PersonMergeStatus;
import gov.va.med.esr.common.model.lookup.Quarter;
import gov.va.med.esr.common.model.lookup.RegistryType;
import gov.va.med.esr.common.model.lookup.RejectionRemark;
import gov.va.med.esr.common.model.lookup.ReportDetailBy;
import gov.va.med.esr.common.model.lookup.ReportDetailFor;
import gov.va.med.esr.common.model.lookup.ReportDivision;
import gov.va.med.esr.common.model.lookup.ReportEEDWeeklyType;
import gov.va.med.esr.common.model.lookup.ReportEligibilityFactorLU;
import gov.va.med.esr.common.model.lookup.ReportExceptionType;
import gov.va.med.esr.common.model.lookup.ReportFacilityDisplayBy;
import gov.va.med.esr.common.model.lookup.ReportFormat;
import gov.va.med.esr.common.model.lookup.ReportLetterFile;
import gov.va.med.esr.common.model.lookup.ReportPeriodType;
import gov.va.med.esr.common.model.lookup.ReportRunFrequency;
import gov.va.med.esr.common.model.lookup.ReportScheduleType;
import gov.va.med.esr.common.model.lookup.StandardReport;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.lookup.VISN;
import gov.va.med.esr.common.model.lookup.VOAFormType;
import gov.va.med.esr.common.model.lookup.WeekOfMonth;
import gov.va.med.esr.common.model.lookup.WkfCaseStatusType;
import gov.va.med.esr.common.model.lookup.WkfCaseType;
import gov.va.med.esr.common.model.report.ReportDayOfWeek;
import gov.va.med.esr.common.model.report.ReportEEDWeeklyReportType;
import gov.va.med.esr.common.model.report.ReportEligibilityFactor;
import gov.va.med.esr.common.model.report.ReportEnrollmentOverrideReason;
import gov.va.med.esr.common.model.report.ReportEnrollmentPriorityGroup;
import gov.va.med.esr.common.model.report.ReportEnrollmentStatus;
import gov.va.med.esr.common.model.report.ReportEnrollmentStatusComponent;
import gov.va.med.esr.common.model.report.ReportFacility;
import gov.va.med.esr.common.model.report.ReportFormType;
import gov.va.med.esr.common.model.report.ReportLetterErrorType;
import gov.va.med.esr.common.model.report.ReportLetterRejectReason;
import gov.va.med.esr.common.model.report.ReportLinkLetterFile;
import gov.va.med.esr.common.model.report.ReportMessageError;
import gov.va.med.esr.common.model.report.ReportPeriod;
import gov.va.med.esr.common.model.report.ReportPersonMergeStatus;
import gov.va.med.esr.common.model.report.ReportQueryToSite;
import gov.va.med.esr.common.model.report.ReportSchedule;
import gov.va.med.esr.common.model.report.BaseReportLookupParameter;
import gov.va.med.esr.common.model.report.ReportBadAddressReason;
import gov.va.med.esr.common.model.report.ReportCancelDeclineReason;
import gov.va.med.esr.common.model.report.ReportFunctionalGroup;
import gov.va.med.esr.common.model.report.ReportMessageType;
import gov.va.med.esr.common.model.report.ReportPHRejectionRemark;
import gov.va.med.esr.common.model.report.ReportParameterSet;
import gov.va.med.esr.common.model.report.ReportRegistryType;
import gov.va.med.esr.common.model.report.ReportSetup;
import gov.va.med.esr.common.model.report.ReportUser;
import gov.va.med.esr.common.model.report.ReportVBAQueryStatus;
import gov.va.med.esr.common.model.report.ReportWkfCaseStatusType;
import gov.va.med.esr.common.model.report.ReportWkfCaseType;
import gov.va.med.esr.common.model.security.ESRUserPrincipal;
import gov.va.med.esr.ui.common.beans.PendingEnrollmentStatus;
import gov.va.med.esr.ui.common.beans.VAFacilityExceptVBA;
import gov.va.med.esr.ui.common.beans.VAMC;
import gov.va.med.esr.ui.common.util.DateUtils;
import gov.va.med.esr.ui.conversion.UIConversionServiceImpl;
import gov.va.med.esr.ui.registry.action.RegistryInfoForm;
import gov.va.med.fw.conversion.ConversionServiceException;
import gov.va.med.fw.model.lookup.Lookup;
import gov.va.med.fw.report.ReportExportedType;
import gov.va.med.fw.util.StringUtils;

/**
 * Conversion service for report actions.
 * 
 *
 * @author Muddaiah Ranga
 * @version 1.0
 */
public class ReportConversionService extends UIConversionServiceImpl implements ReportConstants {

    private static final String[] SUMMARY_ONLY_REPORTS = {"EED6","QM4","QM15"};
    
	public Object convert(Object source, Class targetClass)
	throws ConversionServiceException {
	    return null;
	}

    protected void convertBean(Object source, Object target)
	throws ConversionServiceException {
        // Convert ReportInfoForm to ReportSetup
        if(source instanceof ReportParamInfoForm && target instanceof ReportSetup) {
            this.convertFormToReportSetup((ReportScheduleInfoForm)source,(ReportSetup)target);
        // Convert ReportSetup to RegistryInfoForm
        } else if(target instanceof ReportSetup && source instanceof ReportParamInfoForm) {
            this.convertReportSetupToForm((ReportSetup)source,(ReportParamInfoForm)target);
        }
	}

    private void convertFormToReportSetup(ReportScheduleInfoForm form, ReportSetup reportSetup)
    throws ConversionServiceException {
        ReportParameterSet paramSet = reportSetup.getParameterSet();
        if(paramSet == null) {
            paramSet = new ReportParameterSet();
            reportSetup.setParameterSet(paramSet);
        }

        //Allow only summary for the following reports CR5873
        if(StringUtils.contains(SUMMARY_ONLY_REPORTS,form.getReportIdNoSpace())) {
            form.setReportFormat(ReportFormat.SUMMARY.getCode());
        }
        
        reportSetup.setSetupUser((ESRUserPrincipal)this.getLoggedInUser());
        this.convertFormToReportParameterSet(form,paramSet);

        // The following parameters for scheduling a report not applicable for on demand report
        if(StringUtils.equals(form.getTabName(),TAB_NAME_SCHEDULED_REPORTS)) {
            this.populateReportSchedule(form,reportSetup);

            //Format the emails into comma delimited list
            String[] emails = StringUtils.split(form.getEmailReportTo(),EMAIL_DELIMS);
            if(emails != null && emails.length > 0) {
                StringBuffer buffer = new StringBuffer();
                for(int i=0; i<emails.length; i++) {
                    if(StringUtils.isNotEmpty(emails[i])) {
                        if(buffer.length() > 0) buffer.append(COMMA);
                        buffer.append(emails[i]);
                    }
                }
                reportSetup.setEmail(buffer.toString());
            }
        }
    }

    private void convertFormToReportParameterSet(ReportScheduleInfoForm form, ReportParameterSet paramSet)
    throws ConversionServiceException {
        try {
            if(StringUtils.equals(form.getReportIdNoSpace(),"EED2")) {
	            ImpreciseDate fromYear = DateUtils.getImpreciseDate(form.getFromYear());
	            ImpreciseDate toYear = DateUtils.getImpreciseDate(form.getToYear());
	            //set the year into from and to dates for eed2 report
	            if (fromYear != null) {
	            	int year = fromYear.getCalendar().get(Calendar.YEAR);
	                Calendar calendar = Calendar.getInstance();
	                calendar.clear();
	                calendar.set(year,0,1); //Jan 1st
	                paramSet.setFromDate(calendar.getTime());
	            }

	            if (toYear != null) {
	            	int year = toYear.getCalendar().get(Calendar.YEAR);
	                Calendar calendar = Calendar.getInstance();
	                calendar.clear();
	                calendar.set(year,11,31);	//Dec 31st
	                paramSet.setToDate(calendar.getTime());
	            }
            } else if(StringUtils.equals(form.getReportIdNoSpace(),"EED10")) {
                
                paramSet.setFromDate(null);
                if(StringUtils.isNotEmpty(form.getFromDate())) {
                    ImpreciseDate fromDate = DateUtils.getImpreciseDate(form.getFromDate());                
                    //set the year into from and to dates for eed10 report
                    if (fromDate != null) {
                        int year = fromDate.getCalendar().get(Calendar.YEAR);
                        int month = fromDate.getCalendar().get(Calendar.MONTH);
                        Calendar calendar = Calendar.getInstance();
                        calendar.clear();
                        calendar.set(year,month,1); //First of the month
                        paramSet.setFromDate(calendar.getTime());
                    }
                }
                
                paramSet.setToDate(null);
                if(StringUtils.isNotEmpty(form.getToDate())) {
                    ImpreciseDate toDate = DateUtils.getImpreciseDate(form.getToDate());
                    if (toDate != null) {
                        int year = toDate.getCalendar().get(Calendar.YEAR);
                        int month = toDate.getCalendar().get(Calendar.MONTH);
                        int day = toDate.getCalendar().getActualMaximum(Calendar.DATE);
                        Calendar calendar = Calendar.getInstance();
                        calendar.clear();
                        calendar.set(year,month,day);   //End of the month
                        paramSet.setToDate(calendar.getTime());
                    }
                }
                
                paramSet.setAsOfDate(null);
                if(StringUtils.isNotEmpty(form.getAsOfDate())) {
                    ImpreciseDate asOfDate = DateUtils.getImpreciseDate(form.getAsOfDate());
                    if (asOfDate != null) {
                        int year = asOfDate.getCalendar().get(Calendar.YEAR);
                        int month = asOfDate.getCalendar().get(Calendar.MONTH);
                        int day = asOfDate.getCalendar().getActualMaximum(Calendar.DATE);
                        Calendar calendar = Calendar.getInstance();
                        calendar.clear();
                        calendar.set(year,month,day);   //End of the month
                        paramSet.setAsOfDate(calendar.getTime());
                    }
                }
            } else {
                paramSet.setFromDate(DateUtils.getDate(form.getFromDate()));
                paramSet.setToDate(DateUtils.getDate(form.getToDate()));
                paramSet.setAsOfDate(DateUtils.getDate(form.getAsOfDate()));
            }
            
            paramSet.setPhUnconfirmedDays(this.getInteger(form.getPhUnconfirmedForMoreThan()));

            paramSet.setBeginIncomeYear(this.getInteger(form.getBeginIncomeYear()));
            paramSet.setEndIncomeYear(this.getInteger(form.getEndIncomeYear()));
            paramSet.setDivision((ReportDivision)this.getLookup(ReportDivision.class,form.getDivision()));
            //paramSet.setWorkItemStatus((ReportWorkItemStatus)this.getLookup(ReportWorkItemStatus.class,form.getWorkItemStatus()));

            paramSet.setRunReportByUser(this.getTrueFalse(form.getRunReportByUser()));
            paramSet.setBatchNumber(this.getInteger(form.getBatchNumber()));

            if(StringUtils.equals(form.getExceptionType(),ReportExceptionType.SYSTEM_ERROR.getCode())) {
                paramSet.setExceptionType(null);
            } else {
                paramSet.setExceptionType((ReportExceptionType)this.getLookup(ReportExceptionType.class,form.getExceptionType()));
            }

            paramSet.setIncludeUsers(this.getTrueFalse(form.getIncludeUsers()));

            paramSet.setEnrollmentEffectiveDateOfChange(DateUtils.getDate(form.getEnrollmentEffectiveDateChange()));

            paramSet.setDaysBetweenUpdates(this.getInteger(form.getDaysBetweenUpdates()));

            paramSet.setNumberOfRecordsPerEnrollmentStatus(this.getInteger(form.getRecordsPerEnrollmentStatus()));

            paramSet.setOutlierDays(this.getInteger(form.getOutlierDays()));

            paramSet.setRandomNumberOfRecords(this.getInteger(form.getRandomNumberOfRecords()));

            //Populate Report Enrollment Status Components.
            paramSet.removeAllEnrollmentStatusComponents();
            Set enrollmentStatusComponents = this.getReportLookupParameter(form.getEnrollmentStatusComponent(),EnrollmentStatusComponent.class,ReportEnrollmentStatusComponent.class);
            if(enrollmentStatusComponents != null && !enrollmentStatusComponents.isEmpty()) {
                paramSet.addAllEnrollmentStatusComponents(enrollmentStatusComponents);
            }

            //For QM11 and QM15 these parameters allowed only for detail format.
            if(StringUtils.equals(form.getReportIdNoSpace(),StandardReport.CODE_QM_11.getCode()) ||
               StringUtils.equals(form.getReportIdNoSpace(),StandardReport.CODE_QM_15.getCode()) ||
               StringUtils.equals(form.getReportIdNoSpace(),StandardReport.CODE_QM_3.getCode())) {
                if(!StringUtils.equals(form.getReportFormat(),ReportFormat.DETAIL.getCode())) {
                    paramSet.setOutlierDays(null);
                    paramSet.setRandomNumberOfRecords(null);
                    paramSet.removeAllEnrollmentStatusComponents();
                }
            }

            //Populate Report eligibilityFactors.
            paramSet.removeAllEligibilityFactors();
            Set eligibilityFactors = this.getReportLookupParameter(form.getEligibilityFactors(),ReportEligibilityFactorLU.class,ReportEligibilityFactor.class);
            if(eligibilityFactors != null && !eligibilityFactors.isEmpty()) {
                paramSet.addAllEligibilityFactors(eligibilityFactors);
            }

            //Populate Report PersonMergeStatus.
            paramSet.removeAllPersonMergeStatuses();
            Set personMergeStatuses = this.getReportLookupParameter(form.getPersonMergeStatus(),PersonMergeStatus.class,ReportPersonMergeStatus.class);
            if(personMergeStatuses != null && !personMergeStatuses.isEmpty()) {
                paramSet.addAllPersonMergeStatuses(personMergeStatuses);
            }

            if(!StringUtils.equals(form.getReportFormat(),ReportFormat.DETAIL.getCode())) {
                    paramSet.removeAllPersonMergeStatuses();
            }

            paramSet.setEnrollmentProcessStatus((EnrollmentProcessStatus)this.getLookup(EnrollmentProcessStatus.class,form.getEnrollmentProcessStatus()));

            // Populate report period fields.
            populateReportPeriod(form,paramSet);

            paramSet.setAddressUpdateDays(this.getInteger(form.getAddressUpdatedMultipleTimesWithin()));
            paramSet.setPhUnconfirmedDays(this.getInteger(form.getPhUnconfirmedForMoreThan()));

            // Populates the facilities
            this.populateFacilities(form,paramSet);

            //Populates the query to
            this.populateQueryTo(form,paramSet);

            String reportFormat = form.getReportFormat();
            paramSet.setReportFormat((ReportFormat)this.getLookup(ReportFormat.class,reportFormat));

            paramSet.setDetailFor(null);
            paramSet.setDetailBy(null);
            if(StringUtils.equals(reportFormat,ReportFormat.DETAIL.getCode())) {
                if(StringUtils.equals(form.getReportIdNoSpace(),"QM8")) {
                    paramSet.setDetailFor((ReportDetailFor)this.getLookup(ReportDetailFor.class,form.getUpdateStatus()));
                }
                if(StringUtils.equals(form.getReportIdNoSpace(),"QM17")
                		|| StringUtils.equals(form.getReportIdNoSpace(),"EED9")) {
                    paramSet.setDetailBy((ReportDetailBy)this.getLookup(ReportDetailBy.class,form.getReportDetailBy()));
                }
            }

            paramSet.setFileType((ReportExportedType)this.getLookup(ReportExportedType.class,form.getFileType()));


            // Populate VOA Form types.
            paramSet.removeAllFormTypes();
            String[] formTypeArr = form.getVoaFormTypes();
            if (formTypeArr != null && formTypeArr.length > 0)
            	for (int i = 0; i < formTypeArr.length; i++) 
            		if (formTypeArr[i].equalsIgnoreCase("all")) {
            			formTypeArr = null;
            			break;
            		}
            Set voaFormTypes = getReportLookupParameter(formTypeArr, VOAFormType.class, ReportFormType.class);
            if (voaFormTypes != null && !voaFormTypes.isEmpty()) {
                paramSet.addAllFormTypes(voaFormTypes);
            }

            // Populate Message types.
            paramSet.removeAllMessageTypes();
            Set messageTypes = this.getReportLookupParameter(form.getMessageType(),MessageType.class,ReportMessageType.class);
            if(messageTypes != null && !messageTypes.isEmpty()) {
                paramSet.addAllMessageTypes(messageTypes);
            }

            // Populate Message errors.
            paramSet.removeAllMessageErrors();
            Set messageErrors = this.getMessageErrorReportLookupParameter(form.getMessageError(),AckType.class,ReportMessageError.class);
            if(messageErrors != null && !messageErrors.isEmpty()) {
                paramSet.addAllMessageErrors(messageErrors);
            }

            // Populate bad address reasons.
            paramSet.removeAllBadAddressReasons();
            Set badAddressReasons = this.getReportLookupParameter(form.getBadAddressReason(),BadAddressReason.class,ReportBadAddressReason.class);
            if(badAddressReasons != null && !badAddressReasons.isEmpty()) {
                paramSet.addAllBadAddressReasons(badAddressReasons);
            }

            // Populate Cancel/Decline reasons.
            paramSet.removeAllCancelDeclineReasons();
            Set cancelDeclineReasons = this.getReportLookupParameter(form.getCancelDeclineReason(),CancelDeclineReason.class,ReportCancelDeclineReason.class);
            if(cancelDeclineReasons != null && !cancelDeclineReasons.isEmpty()) {
                paramSet.addAllCancelDeclineReasons(cancelDeclineReasons);
            }

            // Populate Enrollment Override reasons.
            paramSet.removeAllEnrollmentOverrideReasons();
            Set enrollmentOverrideReasons = this.getReportLookupParameter(form.getEnrollmentOverrideReason(), EnrollmentOverrideReason.class, ReportEnrollmentOverrideReason.class);
            if(enrollmentOverrideReasons != null && !enrollmentOverrideReasons.isEmpty()) {
                paramSet.addAllEnrollmentOverrideReasons(enrollmentOverrideReasons);
            }

            // Populate PH Rejection Remarks.
            paramSet.removeAllPHRejectionRemarks();
            Set rejectionRemarks = this.getReportLookupParameter(form.getPhRejectReason(), RejectionRemark.class, ReportPHRejectionRemark.class);
            if(rejectionRemarks != null && !rejectionRemarks.isEmpty()) {
                paramSet.addAllPHRejectionRemarks(rejectionRemarks);
            }

            populateLetterFilesAndRejectErrors(form, paramSet);

            // Populate Functional Groups.
            paramSet.removeAllFunctionalGroups();
            Set functionalGroups = this.getReportLookupParameter(form.getFunctionalGroup(),FunctionalGroup.class,ReportFunctionalGroup.class);
            if(functionalGroups != null && !functionalGroups.isEmpty()) {
                paramSet.addAllFunctionalGroups(functionalGroups);
            }
            // Populate workload case status types
            paramSet.removeAllWkfCaseStatusTypes();
            Set caseStatusTypes = this.getReportLookupParameter(form.getWorkItemStatus(),WkfCaseStatusType.class,ReportWkfCaseStatusType.class);
            if(caseStatusTypes != null && !caseStatusTypes.isEmpty()) {
                paramSet.addAllWkfCaseStatusTypes(caseStatusTypes);
            }

            // Populate workload case types
            paramSet.removeAllWkfCaseTypes();
            Set caseTypes = this.getReportLookupParameter(form.getWorkItemType(),WkfCaseType.class,ReportWkfCaseType.class);
            if(caseTypes != null && !caseTypes.isEmpty()) {
                paramSet.addAllWkfCaseTypes(caseTypes);
            }

            // Populate users.
            paramSet.removeAllUsers();
            Set users = this.getReportUserParameter(form.getReportUser());
            if(users != null && !users.isEmpty()) {
                paramSet.addAllUsers(users);
            }

            // Populate Enrollment Status.
            paramSet.removeAllEnrollmentStatuses();
            Set enrollmentStatuses = this.getReportLookupParameter(form.getEnrollmentStatus(),EnrollmentStatus.class,ReportEnrollmentStatus.class);
            if(enrollmentStatuses != null && !enrollmentStatuses.isEmpty()) {
                paramSet.addAllEnrollmentStatuses(enrollmentStatuses);
            }

            //Populate Pending Enrollment Status.
            String[] pendingEnrollmentStatus = form.getPendingEnrollmentStatus();
            if(pendingEnrollmentStatus != null && pendingEnrollmentStatus.length > 0) {
                paramSet.removeAllEnrollmentStatuses();
                Set pendingEnrollmentStatuses = this.getReportLookupParameter(pendingEnrollmentStatus,PendingEnrollmentStatus.class,ReportEnrollmentStatus.class);
                if(pendingEnrollmentStatuses != null && !pendingEnrollmentStatuses.isEmpty()) {
                    paramSet.addAllEnrollmentStatuses(pendingEnrollmentStatuses);
                }
            }

            // Populate Enrollment Category.
            //paramSet.removeAllEnrollmentCategories();
            //Set enrollmentCategories = this.getReportLookupParameter(form.getEnrollmentCategory(),EnrollmentCategory.class,ReportEnrollmentCategory.class);
            //if(enrollmentCategories != null && !enrollmentCategories.isEmpty()) {
            //    paramSet.addAllEnrollmentCategories(enrollmentCategories);
            //}

            // Populate registry types.
            paramSet.removeAllRegistryTypes();
            Set registryTypes = this.getReportLookupParameter(form.getRegistryType(),RegistryType.class,ReportRegistryType.class);
            if(registryTypes != null && !registryTypes.isEmpty()) {
                paramSet.addAllRegistryTypes(registryTypes);
            }

            // Populate reports.
            paramSet.removeAllReportEEDWeeklyReportTypes();
            Set reportEEDWeeklyReportTypes = this.getReportLookupParameter(form.getEedWeeklyReport(),ReportEEDWeeklyType.class,ReportEEDWeeklyReportType.class);
            if(reportEEDWeeklyReportTypes != null && !reportEEDWeeklyReportTypes.isEmpty()) {
                paramSet.addAllReportEEDWeeklyReportTypes(reportEEDWeeklyReportTypes);
            }

            // Populate priority groups.
            paramSet.removeAllReportEnrollmentPriorityGroups();
            Set enrollmentPriorityGroups = this.getReportEnrollmentPriorityGroups(form.getPriorityGroup());
            if(enrollmentPriorityGroups != null && !enrollmentPriorityGroups.isEmpty()) {
                paramSet.addAllReportEnrollmentPriorityGroups(enrollmentPriorityGroups);
            }

            paramSet.removeAllVBAQueryStatuses();
            Set vbaQueryStatuses = this.getReportLookupParameter(
            		form.getVbaQueryStatus(),AACIndicator.class,ReportVBAQueryStatus.class);
            if(vbaQueryStatuses != null && !vbaQueryStatuses.isEmpty()) {
                paramSet.addAllVBAQueryStatuses(vbaQueryStatuses);
            }
        }catch(ConversionServiceException cEx) {
            throw cEx;
        } catch(Exception ex) {
            throw new ConversionServiceException("Error while converting form to bom",ex);
        }
    }

    private void convertReportSetupToForm(ReportSetup reportSetup, ReportParamInfoForm form)
    throws ConversionServiceException {
    }

    private void populateLetterFilesAndRejectErrors(ReportParamInfoForm form, ReportParameterSet paramSet) throws ConversionServiceException {
        paramSet.removeAllReportLinkLetterFiles();
        Set letterFiles = this.getReportLookupParameter(form.getLetterFile(), ReportLetterFile.class, ReportLinkLetterFile.class);
        if (letterFiles != null && letterFiles.isEmpty()==false) {
        	paramSet.addAllReportLinkLetterFiles(letterFiles);
        }

        // Populate Letter RejectReasons and ErrorTypes
        paramSet.removeAllLetterRejectReasons();
        paramSet.removeAllLetterErrorTypes();
        paramSet.setAllLetterRejectReasons(false);
        paramSet.setAllLetterErrorTypes(false);
        String[] letterRejectErrors = new String[0];
        String[] letterRejects = new String[0];
        String[] letterErrors = new String[0];

        Set reportLetterFileCodes = paramSet.getReportLetterFileCodes();

        if (reportLetterFileCodes.contains(ReportLetterFile.ERROR.getCode()) &&
        		reportLetterFileCodes.contains(ReportLetterFile.CODE_1_REJECT.getCode())) {
        	letterRejectErrors = form.getLetterRejectErrorReason();
        }
        else if (reportLetterFileCodes.contains(ReportLetterFile.ERROR.getCode())) {
        	letterErrors = form.getLetterErrorType();
        }
        else if (reportLetterFileCodes.contains(ReportLetterFile.CODE_1_REJECT.getCode())) {
        	letterRejects = form.getLetterRejectReason();
        }

        if (reportLetterFileCodes.isEmpty()) {
        		paramSet.setAllLetterRejectReasons(true);
        		paramSet.setAllLetterErrorTypes(true);
        }
        else {

    		if (form.getAllLetterRejectErrorReasonSelected()) {
    			paramSet.setAllLetterRejectReasons(true);
        		paramSet.setAllLetterErrorTypes(true);
    		}
    		else {
    			if (letterRejectErrors.length > 0) {
    				ArrayList letterRejectsList = new ArrayList();
    				ArrayList letterErrorsList = new ArrayList();
	    			for (int i=0; i < letterRejectErrors.length; i++) {
	    				String prefixedCode = (String)letterRejectErrors[i];
	    				if (prefixedCode.startsWith(ReportConstants.ERROR_CODE_PREFIX)) {
	    					String code = prefixedCode.substring(ReportConstants.ERROR_CODE_PREFIX.length());
	    					letterErrorsList.add(code);
	    				}
	    				else if (prefixedCode.startsWith(ReportConstants.REJECT_CODE_PREFIX)) {
	    					String code = prefixedCode.substring(ReportConstants.REJECT_CODE_PREFIX.length());
	    					letterRejectsList.add(code);
	    				}
	    			}
	    			letterRejects = (String[])letterRejectsList.toArray(new String[0]);
	    			letterErrors = (String[])letterErrorsList.toArray(new String[0]);
    			}

	    		if (letterRejects.length > 0 || letterErrors.length > 0) {
		        	if (letterRejects.length > 0) {
		        		if (form.getAllLetterRejectReasonSelected()) {
		        			paramSet.setAllLetterRejectReasons(true);
		        		}
		        		else {
		        			Set x = this.getReportLookupParameter(letterRejects, ComAACRejectReasonType.class, ReportLetterRejectReason.class);
		        			if (x != null && x.isEmpty()==false) {
		        				paramSet.addAllLetterRejectReasons(x);
		        			}
		        		}
		        	}

		        	if (letterErrors.length > 0) {
		        		if (form.getAllLetterErrorTypeSelected()) {
		        			paramSet.setAllLetterErrorTypes(true);
		        		}
		        		else {
		        			Set x = this.getReportLookupParameter(letterRejects, ComAACErrorType.class, ReportLetterErrorType.class);
		        			if (x != null && x.isEmpty()==false) {
		        				paramSet.addAllLetterErrorTypes(x);
		        			}
		        		}
		        	}
	    		}
	    		else {
	    			if (reportLetterFileCodes.contains(ReportLetterFile. CODE_1_REJECT.getCode())) {
	    				paramSet.setAllLetterRejectReasons(true);
	    			}
	    			if (reportLetterFileCodes.contains(ReportLetterFile.ERROR.getCode())) {
	    				paramSet.setAllLetterErrorTypes(true);
	    			}
	    		}
    		}
        }
    }

    private void populateReportPeriod(ReportParamInfoForm form, ReportParameterSet parameSet) throws ConversionServiceException {
        parameSet.setReportPeriod(null);
        String reportPeriodType = form.getReportPeriodType();
        if(StringUtils.isNotEmpty(reportPeriodType)) {
            ReportPeriod reportPeriod = new ReportPeriod();
            if(StringUtils.equals(form.getTabName(),TAB_NAME_SCHEDULED_REPORTS)) {
                String generateReport = ((ReportScheduleInfoForm)form).getGenerateReportNoDefault();
                if(StringUtils.equals(generateReport,ReportRunFrequency.OTHER.getCode()) && StringUtils.equals(reportPeriodType,ReportPeriodType.CODE_DATE_RANGE.getName())) {
                    parameSet.setReportPeriod(reportPeriod);
                    reportPeriod.setFromDate(DateUtils.getDate(form.getReportPeriodStartDate()));
                    reportPeriod.setToDate(DateUtils.getDate(form.getReportPeriodEndDate()));
                }
            } else {
                parameSet.setReportPeriod(reportPeriod);
                reportPeriod.setType((ReportPeriodType)this.getLookup(ReportPeriodType.class,form.getReportPeriodType()));
                if(StringUtils.equals(reportPeriodType,ReportPeriodType.CODE_ALL_FISCAL_YEARS.getName())){
                	 //reportPeriod.setYear(this.getInteger(form.getReportPeriodSummaryYear()));
                    reportPeriod.setYear(new Integer(
                            gov.va.med.fw.util.DateUtils.getFiscalYear(
                                    DateUtils.getDate(form.getAsOfDate()))));
                }else if(StringUtils.equals(reportPeriodType,ReportPeriodType.CODE_FISCAL_YEAR.getName())) {
                    reportPeriod.setYear(this.getInteger(form.getReportPeriodYear()));
                } else if(StringUtils.equals(reportPeriodType,ReportPeriodType.CODE_QUARTERLY.getName())) {
                    reportPeriod.setYear(this.getInteger(form.getReportPeriodQuarterYear()));
                    reportPeriod.setQuarter((Quarter)this.getLookup(Quarter.class,form.getReportPeriodQuarter()));
                } else if(StringUtils.equals(reportPeriodType,ReportPeriodType.CODE_DATE_RANGE.getName())) {
                    reportPeriod.setFromDate(DateUtils.getDate(form.getReportPeriodStartDate()));
                    reportPeriod.setToDate(DateUtils.getDate(form.getReportPeriodEndDate()));
                }
            }
        }
    }

    private void populateReportSchedule(ReportScheduleInfoForm form, ReportSetup reportSetup) throws ConversionServiceException {

        String generateReport = form.getGenerateReportNoDefault();
        if(StringUtils.isNotEmpty(generateReport)) {
            ReportSchedule schedule = new ReportSchedule();
            reportSetup.setSchedule(schedule);

            schedule.setRunFrequency((ReportRunFrequency)this.getLookup(ReportRunFrequency.class,generateReport));

            String scheduleType = form.getScheduleType();
            if(StringUtils.equals(generateReport,ReportRunFrequency.DAILY_WEEKLY.getCode())) {

                scheduleType = ReportScheduleType.DAY_OF_WEEK.getCode();
                Set dayOfWeeks = this.getReportLookupParameter(form.getDailyWeeklyDay(),DayOfWeek.class,ReportDayOfWeek.class);
                if(dayOfWeeks != null && !dayOfWeeks.isEmpty()) {
                    schedule.addAllDaysOfWeek(dayOfWeeks);
                }

            } else if(StringUtils.equals(generateReport,ReportRunFrequency.MONTHLY.getCode())) {

                 if(StringUtils.equals(scheduleType,ReportScheduleType.DAY_OF_MONTH.getCode())) {
                     schedule.setDayOfMonth((DayOfMonth)this.getLookup(DayOfMonth.class,form.getMonthlyDayOfEveryMonthNoDefault()));
                 } else if(StringUtils.equals(scheduleType,ReportScheduleType.WEEK_DAY.getCode())) {
                     schedule.setWeekOfMonth((WeekOfMonth)this.getLookup(WeekOfMonth.class,form.getMonthlyWeekOfEveryMonthNoDefault()));
                     schedule.setDayOfWeek((DayOfWeek)this.getLookup(DayOfWeek.class,form.getMonthlyDayOfEveryWeekNoDefault()));
                 }

            } else if(StringUtils.equals(generateReport,ReportRunFrequency.QUARTERLY.getCode())) {

                scheduleType = ReportScheduleType.DAY_OF_QUARTER.getCode();
                schedule.setDayOfQuarter((DayOfQuarter)this.getLookup(DayOfQuarter.class,form.getQuarterlyDayOfQuarterNoDefault()));

            } else if(StringUtils.equals(generateReport,ReportRunFrequency.YEARLY.getCode())) {

                if(StringUtils.equals(scheduleType,ReportScheduleType.MONTH_DAY.getCode())) {

                    schedule.setMonth((Month)this.getLookup(Month.class,form.getYearlyMonthOfYearNoDefault()));
                    schedule.setNumericDayOfMonth(this.getInteger(form.getYearlyDayOfMonthNoDefault()));

                } else if(StringUtils.equals(scheduleType,ReportScheduleType.WEEK_DAY_MONTH.getCode())) {

                    schedule.setWeekOfMonth((WeekOfMonth)this.getLookup(WeekOfMonth.class,form.getYearlyWeekOfMonthNoDefault()));
                    schedule.setDayOfWeek((DayOfWeek)this.getLookup(DayOfWeek.class,form.getYearlyDayOfWeekNoDefault()));
                    schedule.setMonth((Month)this.getLookup(Month.class,form.getYearlyMonthNoDefault()));
                }

            } else if(StringUtils.equals(generateReport,ReportRunFrequency.OTHER.getCode())) {

            	 	scheduleType = ReportScheduleType.DATE.getCode();
                    schedule.setDateToGenerate(DateUtils.getDate(form.getOtherDateToGenerateReport()));
            }
            if(StringUtils.isNotEmpty(scheduleType)) {
                schedule.setScheduleType((ReportScheduleType)this.getLookup(ReportScheduleType.class,scheduleType));
            }

            //Populate Time to generate report
            schedule.setHour(this.getInteger(form.getTimeToGenerateReportHourNoDefault()));
            schedule.setMinute(this.getInteger(form.getTimeToGenerateReportMinuteNoDefault()));
        }
    }

    private Set getReportEnrollmentPriorityGroups(String[] code) throws ConversionServiceException {
        if(code == null || code.length == 0) return null;
        Set ePriorityGroup = new HashSet();
        try {
            if(StringUtils.contains(code,ALL)) {
                Collection ePriorityGroups = this.getLookupCacheService().getFromCache(EnrollmentPriorityGroup.class.getName());
                Collection ePrioritySubGroups = this.getLookupCacheService().getFromCache(EnrollmentPrioritySubGroup.class.getName());

                ReportEnrollmentPriorityGroup reportLookupParam = null;
                for(Iterator iter=ePriorityGroups.iterator(); iter.hasNext();) {
                    EnrollmentPriorityGroup priorityGroupLookup = (EnrollmentPriorityGroup)iter.next();
                    if(StringUtils.equals(priorityGroupLookup.getCode(),EnrollmentPriorityGroup.GROUP_7.getName()) || StringUtils.equals(priorityGroupLookup.getCode(),EnrollmentPriorityGroup.GROUP_8.getName())) {
                        for(Iterator subIter=ePrioritySubGroups.iterator(); subIter.hasNext();) {
                            reportLookupParam = (ReportEnrollmentPriorityGroup)ReportEnrollmentPriorityGroup.class.newInstance();
                            reportLookupParam.setEnrollmentPriorityGroup(priorityGroupLookup);
                            EnrollmentPrioritySubGroup prioritySubGroupLookup = (EnrollmentPrioritySubGroup)subIter.next();
                            reportLookupParam.setEnrollmentPrioritySubGroup(prioritySubGroupLookup);
                            if(reportLookupParam != null) ePriorityGroup.add(reportLookupParam);
                        }
                    } else {
                        reportLookupParam = (ReportEnrollmentPriorityGroup)ReportEnrollmentPriorityGroup.class.newInstance();
                        reportLookupParam.setEnrollmentPriorityGroup(priorityGroupLookup);
                        if(reportLookupParam != null) ePriorityGroup.add(reportLookupParam);
                    }
                    if(reportLookupParam != null) ePriorityGroup.add(reportLookupParam);
                }
            } else {

                    for(int i=0; i<code.length; i++) {
                        if(StringUtils.isEmpty(code[i])) continue;

                        String[] codes = StringUtils.split(code[i],COMMA);
                        String priorityCode = codes[0];
                        String prioritySubCode = (codes.length > 1) ? codes[1] : null;
                        EnrollmentPriorityGroup priorityGroupLookup = (EnrollmentPriorityGroup)this.getLookup(EnrollmentPriorityGroup.class,priorityCode);

                        ReportEnrollmentPriorityGroup reportLookupParam = null;
                        if(priorityGroupLookup != null) {
                            reportLookupParam = (ReportEnrollmentPriorityGroup)ReportEnrollmentPriorityGroup.class.newInstance();
                            reportLookupParam.setEnrollmentPriorityGroup(priorityGroupLookup);
                            EnrollmentPrioritySubGroup prioritySubGroupLookup = (EnrollmentPrioritySubGroup)this.getLookup(EnrollmentPrioritySubGroup.class,prioritySubCode);
                            if(prioritySubGroupLookup != null) {
                                reportLookupParam.setEnrollmentPrioritySubGroup(prioritySubGroupLookup);
                            }
                            if(reportLookupParam != null) ePriorityGroup.add(reportLookupParam);
                        }
                    }
            }
        } catch(Exception ex) {
            throw new ConversionServiceException("Error while creating EnrollmentPriorityGroups",ex);
        }
        return ePriorityGroup;
    }

    private void populateFacilities(ReportScheduleInfoForm form, ReportParameterSet paramSet) throws ConversionServiceException {
        String facilityDisplayBy = form.getFacilityDisplayByNoDefault();
        paramSet.setFacilityDisplayBy((ReportFacilityDisplayBy)this.getLookup(ReportFacilityDisplayBy.class,facilityDisplayBy));
        Set facilities = null;
        if(StringUtils.equals(facilityDisplayBy,ReportFacilityDisplayBy.CODE_VISN.getCode())) {
            facilities = this.getVISNFacilities(merge(form.getVisn(),form.getStationNumbersAsArray()));
        } else if(StringUtils.equals(facilityDisplayBy,ReportFacilityDisplayBy.CODE_VISN_SITE.getCode())) {
            facilities = this.getFacilitiesForVisnSite(merge(form.getVisnFacility(),form.getStationNumbersAsArray()));
        } else if(StringUtils.equals(facilityDisplayBy,ReportFacilityDisplayBy.CODE_SITE.getCode())) {
            facilities = this.getFacilitiesForSite(merge(form.getFacility(),form.getStationNumbersAsArray()));
        }else if(StringUtils.equals(facilityDisplayBy,ReportFacilityDisplayBy.CODE_VAMC.getCode())) {
            facilities = this.getFacilitiesForVISNVAMCSite(merge(form.getVamcs(),form.getStationNumbersAsArray()));
        } else if(StringUtils.equals(facilityDisplayBy,ReportFacilityDisplayBy.CODE_VAMC_SITE.getCode())) {
            facilities = this.getFacilitiesForVISNVAMCSite(merge(form.getVamcFacility(),form.getStationNumbersAsArray()));
        } else if(StringUtils.equals(facilityDisplayBy,ReportFacilityDisplayBy.CODE_VISN_VAMC_SITE.getCode())) {
            facilities = this.getFacilitiesForVISNVAMCSite(merge(form.getVisnVamcFacility(),form.getStationNumbersAsArray()));
        }else if(StringUtils.equals(facilityDisplayBy,ReportFacilityDisplayBy.CODE_VISN_VAMC.getCode())) {
            facilities = this.getFacilitiesForVISNVAMCSite(merge(form.getVisnVamc(),form.getStationNumbersAsArray()));
        }
        paramSet.removeAllFacilities();
        if(facilities != null) {
            for(Iterator iter = facilities.iterator(); iter.hasNext();) {
                VAFacility facility = (VAFacility)iter.next();
                if(facility != null) {
                    ReportFacility reportFacility = new ReportFacility();
                    reportFacility.setFacility(facility);
                    paramSet.addFacility(reportFacility);
                }
            }
        }
    }

 /**
  *
  * @param code
  * @return facilities
  * @throws ConversionServiceException
  */
    private Set getFacilitiesForVISNVAMCSite(String[] code) throws ConversionServiceException {
        Set facilities = new HashSet();
        try{
        if(code != null && code.length > 0) {
        	// If it is all return empty list.
            if(StringUtils.contains(code,ALL)) {
                facilities = new HashSet();
                //If it is ALL_VAMCs, get all VAMCs and add it to the List.
            }else if(StringUtils.contains(code,ALL_VAMCS)){
            	Collection vamcs = this.getLookupCacheService().getFromCache(VAMC.class.getName());
            	if(vamcs!=null)
            		facilities.addAll(vamcs);
            } else {
            	//Get All VAMCs
            	Collection vamcs = this.getLookupCacheService().getFromCache(VAMC.class.getName());
            	// Get Parent Id --> List of Facilities.
            	Map parentSiteMap=getLookupCacheService().getParentSiteMap();
                VAFacility vamc=null;
                VAFacility facility=null;
                Set visnCode = new HashSet();
                for(int i=0; i<code.length; i++) {
                    if(StringUtils.isNotEmpty(code[i])) {
                    	//If it is of type VISN add it to VISN collection.
                    	 if(code[i].startsWith(VISN)) {
                             visnCode.add(code[i]);
                         } else {
                        	 // If it is VAMC add it to collection, and also get all it childrens and add it to collection.
	                    	vamc=getVAMC(vamcs,code[i]);
	                        if(vamc!=null) {
	                        	facilities.add(vamc);
	                        	List vamcSites=(List)parentSiteMap.get(vamc.getIdentifier());
	                        	if(vamcSites!=null)
	                        		facilities.addAll(vamcSites);
	                        } else {
	                        	// If it is not VAMC, it could be a regular site, add to collection.
	                        	facility = (VAFacility)this.getLookup(VAFacility.class,code[i]);
	                        	if(facility != null) facilities.add(facility);
	                        }
		                  }
                    }
                }
                // Get all facilities under this VISN and add it to collection.
                Set lookups = getFacilitiesForVisnVamc(getStringArrayFromSet(visnCode),parentSiteMap);
                if(lookups != null) {
                    facilities.addAll(lookups);
                }
              }
            }
        }catch(Exception ex) {
            throw new ConversionServiceException("Error while getting VISN/VAMC/Site map",ex);
        }

        return facilities;
    }
    /**
     *
     * @param code
     * @param parentSiteMap
     * @return
     * @throws ConversionServiceException
     */
    private Set getFacilitiesForVisnVamc(String[] code, Map parentSiteMap) throws ConversionServiceException {
        Set facilities = new HashSet();
        //Get all VISNs
        Set lookups = this.getLookups(VISN.class,code);
        if(lookups != null && !lookups.isEmpty()) {
            try {
            	//Get VISN --> List of VAMCs
                Map visnVamcMap = getLookupCacheService().getVISNVAMCMap();
                // Loop through VAMCs and add it to collection.
                for(Iterator iter=lookups.iterator(); iter.hasNext();) {
                    List list = (List)visnVamcMap.get(iter.next());
                    if(list != null && !list.isEmpty()) {
                    	for(Iterator it=list.iterator();it.hasNext();){
                    		VAFacility vamc=(VAFacility)it.next();
                    		facilities.add(vamc);
                    		// Add all its children are also to the collection.
                    		List sites=(List)parentSiteMap.get(vamc.getIdentifier());
                    		if(sites!=null)
                    			facilities.addAll(sites);
                    	}
                    }
                }
            } catch(Exception ex) {
                throw new ConversionServiceException("Error while getting VISN/VAMC map",ex);
            }
        }
        return facilities;
    }
    /**
     *
     * @param vamcs
     * @param code
     * @return
     */
    private VAFacility getVAMC(Collection vamcs, String code)
    {
    	if(vamcs!=null)
    	{
    		VAFacility site=null;
    		for (Iterator it=vamcs.iterator();it.hasNext();)
    		{
    			site=(VAFacility)it.next();
    			if(site.getCode().equals(code))
    			{
    				return site;
    			}

    		}
    	}
    	return null;
    }


    private Set getVISNFacilities(String[] code) throws ConversionServiceException {
        Set lookups = null;
        try {
            if(code != null && code.length > 0) {
                if(StringUtils.contains(code,ALL)) {
                    Collection visns = this.getLookupCacheService().getFromCache(VISN.class.getName());
                    lookups = new HashSet();
                    if(visns != null) {
                        VAFacility facility = null;
                        VISN visn = null;
                        for(Iterator iter=visns.iterator(); iter.hasNext();) {
                            visn = (VISN)iter.next();
                            facility = (visn != null) ? (VAFacility)this.getLookupByName(VAFacility.class,visn.getCode()) : null;
                            if(facility != null) lookups.add(facility);
                        }
                        
                        VAFacility noVISNFacility = new VAFacility();
                        noVISNFacility.setVisnId(gov.va.med.esr.common.model.lookup.VISN.CODE_NO_VISN_IDENTIFIER);
                    	lookups.add(noVISNFacility);
                    }
                } else {
                    lookups = new HashSet();
                    VAFacility facility = null;
                    for(int i=0; i<code.length; i++) {
                        if(StringUtils.equals(gov.va.med.esr.common.model.lookup.VISN.CODE_NO_VISN.getCode(), code[i])){
                            //Add a dummy facility for No VISN
                        	facility = new VAFacility();
                        	facility.setVisnId(gov.va.med.esr.common.model.lookup.VISN.CODE_NO_VISN_IDENTIFIER);
                        }else {
                        	facility = (VAFacility)this.getLookupByName(VAFacility.class,code[i]);
                        }
                        
                        if(facility != null) lookups.add(facility);
                    }
                }
            }
        } catch(Exception ex) {
            throw new ConversionServiceException("Error while getting VISN lookup object VAFacility and name = " + code,ex);
        }
        return lookups;
    }

    private Set getFacilitiesForVisn(String[] code)
			throws ConversionServiceException {

        //Facilites for all selected VISNs
        Set facilities = new HashSet();
        
        if (code == null || code.length == 0) 
            return facilities;
		//VISN codes without the No VISN option
    	List validCodes = new ArrayList();
    			
		//Map of VISN-->Sites
		Map visnSiteMap = null;		
		
		try {
			visnSiteMap = getLookupCacheService().getVISNSiteMap();

		} catch (Exception ex) {
			throw new ConversionServiceException(
					"Error while getting VISN/Site map", ex);
		}

		for (int i = 0; i < code.length; i++) {
			String currentCode = code[i];
			//For No VISN selection, get all facilities without VISN and add them to the facilities list
			if (gov.va.med.esr.common.model.lookup.VISN.CODE_NO_VISN.getCode()
					.equals(currentCode)) {
				
				List list = (List) visnSiteMap	
						.get(gov.va.med.esr.common.model.lookup.VISN.getNoVISN());
				
				if (list != null && (!list.isEmpty())) {
					facilities.addAll(list);
				}
			} else {
				validCodes.add(currentCode);
			}
		}
		
		Set lookups = null;
		//Look up the List of VISNs based on the VISN codes
		if(!validCodes.isEmpty()){
			
			String[]  validCodesArr = new String[validCodes.size()];
			
			for (int i =0 ; i < validCodes.size(); i++) {
				validCodesArr[i] = (String)validCodes.get(i);
			}
			
			lookups = this.getLookups(VISN.class, validCodesArr);
		}
		
		if (lookups != null && !lookups.isEmpty()) {
			for (Iterator iter = lookups.iterator(); iter.hasNext();) {
				List list = (List) visnSiteMap.get(iter.next());
				if (list != null && !list.isEmpty()) {
					facilities.addAll(list);
				}
			}
		}

		return facilities;
	}

    private Set getFacilitiesForVisnSite(String[] code) throws ConversionServiceException {
        Set facilities = new HashSet();
        if(code != null && code.length > 0) {
            if(StringUtils.contains(code,ALL)) {
                facilities = new HashSet();
            } else {
                Set visnCode = new HashSet();
                Set facilityCode = new HashSet();
                for(int i=0; i<code.length; i++) {
                    if(StringUtils.isNotEmpty(code[i])) {
                        if(code[i].startsWith(gov.va.med.esr.common.model.lookup.VISN.CODE_NO_VISN.getCode()) 
                        		|| code[i].startsWith(VISN) || code[i].equals(ALL)) {
                            visnCode.add(code[i]);
                        } else {
                            facilityCode.add(code[i]);
                        }
                    }
                }
                Set lookups = getFacilitiesForVisn(getStringArrayFromSet(visnCode));
                if(lookups != null) {
                    facilities.addAll(lookups);
                }
                lookups = this.getLookups(VAFacility.class,getStringArrayFromSet(facilityCode));
                if(lookups != null) {
                    facilities.addAll(lookups);
                }
            }
        }
        return facilities;
    }

    private Set getFacilitiesForSite(String[] code) throws ConversionServiceException {
        Set facilities = null;
        if(code != null && code.length > 0) {
            if(StringUtils.contains(code,ALL)) {
                facilities = new HashSet();
            } else {
                facilities = this.getLookups(VAFacility.class,code);
            }
        }
        return facilities;
    }

    private void populateQueryTo(ReportScheduleInfoForm form, ReportParameterSet paramSet) throws ConversionServiceException {
        String queryTo[] = form.getQueryTo();
        Collection facilities = null;

        if(StringUtils.contains(queryTo,ALL_SITES)) {
            facilities = getLookups(VAFacilityExceptVBA.class);
        } else if(StringUtils.contains(queryTo,ALL_SITES_AND_VBA)) {
            facilities = this.getLookups(VAFacility.class);
        } else if(StringUtils.contains(queryTo,VBA)) {
            facilities = this.getLookups(VAFacility.class,queryTo);
        }
        paramSet.removeAllQueryToSites();
        if(facilities != null) {
            for(Iterator iter = facilities.iterator(); iter.hasNext();) {
                VAFacility facility = (VAFacility)iter.next();
                if(facility != null) {
                    ReportQueryToSite reportQueryToSite = new ReportQueryToSite();
                    reportQueryToSite.setQueryToSite(facility);
                    paramSet.addQueryToSite(reportQueryToSite);
                }
            }
        }
    }

    private Set getReportUserParameter(String[] code) throws ConversionServiceException {
        if(code == null || code.length == 0) return null;
        Set reportParam = null;
        try {
            reportParam = new HashSet();
            for (int i=0; i < code.length; i++) {
            	String code1 = code[i];
            	if (ReportConstants.ALL.equals(code1)) {continue;};
            	ESRUserPrincipal user =  this.getUserAdminService().findUserByName(code1);
            	ReportUser reportUser = new ReportUser();
                reportUser.setUser(user);
                reportParam.add(reportUser);
            }
        } catch(Exception ex) {
            throw new ConversionServiceException("Error while converting " + ESRUserPrincipal.class.getName(),ex);
        }
        return reportParam;
    }

    private Set getMessageErrorReportLookupParameter(String code, Class lookupType,Class reportParamType) throws ConversionServiceException {
        if(StringUtils.isEmpty(code)) return null;
        Set reportParam = null;
        if(StringUtils.equals(code,ALL)) {
            String[] codes = new String[2];
            codes[0] = AckType.CODE_AE.getCode();
            codes[1] = AckType.CODE_AR.getCode();
            reportParam = getReportLookupParameter(codes,lookupType,reportParamType);
        } else {
            reportParam = getReportLookupParameter(code,lookupType,reportParamType);
        }
        return reportParam;
    }

    private Set getReportLookupParameter(String code, Class lookupType,Class reportParamType) throws ConversionServiceException {
        if(StringUtils.isEmpty(code)) return null;
        String[] codes = new String[1];
        codes[0] = code;
        return this.getReportLookupParameter(codes,lookupType,reportParamType);
    }

    private Set getReportLookupParameter(String[] code, Class lookupType,Class reportParamType) throws ConversionServiceException {
        if(code == null || code.length == 0) return null;
        Set lookups = this.getLookups(lookupType,code);
        Set reportParam = null;
        if(lookups != null && !lookups.isEmpty()) {
            try {
                reportParam = new HashSet();
                for(Iterator iter=lookups.iterator(); iter.hasNext();) {
                    BaseReportLookupParameter lookupParameter = this.createReportLookupParameter((Lookup)iter.next(),reportParamType);
                    reportParam.add(lookupParameter);
                }

            } catch(ConversionServiceException cEx) {
                throw cEx;
            }
            catch(Exception ex) {
                throw new ConversionServiceException("Error while converting " + reportParamType.getName(),ex);
            }
        }
        return reportParam;
    }

    private BaseReportLookupParameter createReportLookupParameter(Lookup lookup,Class reportParamType) throws ConversionServiceException {
        try {
            BaseReportLookupParameter lookupParameter = (BaseReportLookupParameter)reportParamType.newInstance();
            lookupParameter.setLookup(lookup);
            return lookupParameter;
        } catch(Exception ex) {
            throw new ConversionServiceException("Error while creating report lookup parameter " + reportParamType.getName(),ex);
        }
    }

    private Set getLookups(Class clazz,String[] code) throws ConversionServiceException {
        Set lookups = null;
        try {
            if(code != null && code.length > 0) {
                if(StringUtils.contains(code,ALL)) {
                    lookups  = new HashSet(this.getLookupCacheService().getFromCache(clazz.getName()));
                } else {
                    lookups = new HashSet();
                    Lookup lookup = null;
                    for(int i=0; i<code.length; i++) {
                        lookup = this.getLookup(clazz,code[i]);
                        if(lookup != null) lookups.add(this.getLookup(clazz,code[i]));
                    }
                }
            }
        } catch(Exception ex) {
            throw new ConversionServiceException("Error while getting lookup object for type = " + clazz.getName() + " code = " + code,ex);
        }
        return lookups;
    }

//    private Lookup getLookup(Class clazz,String code) throws ConversionServiceException {
//        try {
//            return (StringUtils.isNotEmpty(code)) ? this.getLookupCacheService().getByCodeFromCache(clazz,code) : null;
//        } catch(Exception ex) {
//            throw new ConversionServiceException("Error while getting lookup object for type = " + clazz.getName() +"  code = " + code,ex);
//        }
//    }

    private Collection getLookups(Class clazz) throws ConversionServiceException {
        try {
            return  this.getLookupCacheService().getFromCache(clazz.getName());
        } catch(Exception ex) {
            throw new ConversionServiceException("Error while getting lookup object for type = " + clazz.getName(),ex);
        }
    }

    private Lookup getLookupByName(Class clazz,String name)
    throws ConversionServiceException {
        Lookup lookup = null;
        try {
            if(StringUtils.isNotEmpty(name)) {
                lookup = this.getLookupCacheService().getLookupService().getByName(clazz,name);
            }
        } catch(Exception ex) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("Error while getting lookup object for ");
            buffer.append(" type = " + clazz.getName());
            buffer.append(" name = " + name);
            throw new ConversionServiceException(buffer.toString(),ex);
        }
        return lookup;
    }

    private Integer getInteger(String value) {
        return StringUtils.isNotEmpty(value) ? new Integer(value) : null;
    }

    private boolean getTrueFalse(String flag) {
        return StringUtils.equals(flag,RegistryInfoForm.Y) ? true : false;
    }

    protected static void setPrivateFieldData(Object obj,Class clazz, String methodName, Object data) {
        try {
            final Method[] methods = clazz.getDeclaredMethods();

            for (int i=0; i<methods.length; i++) {
                if (methods[i].getName().equals(methodName)) {
                    final Object params[] = new Object[1];
                    params[0] = data;
                    methods[i].setAccessible(true);
                    methods[i].invoke(obj,params);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String[] merge(String[] setOne, String[] SetTwo){
        Set newSet = new HashSet();

        if (setOne != null && setOne.length > 0){
            for (int i=0; i<setOne.length; i++){
                newSet.add(setOne[i]);
            }
        }

        if (SetTwo != null && SetTwo.length > 0){
            for (int i=0; i<SetTwo.length; i++){
                newSet.add(SetTwo[i]);
            }
        }

        return getStringArrayFromSet(newSet);
    }

    private String[] getStringArrayFromSet(Set set) {
        if(set == null || set.isEmpty()) return null;
        String[] code = new String[set.size()];
        int i = 0;
        for(Iterator iter=set.iterator(); iter.hasNext();) {
            String string = (String)iter.next();
            if(StringUtils.isNotEmpty(string)) {
                code[i] = string;
                i = i + 1;
            }
        }
        return code;
    }
}