//#############################################################################
//#                                                                           #
//#  Copyright (C) <2015>  <IMS MAXIMS>                                       #
//#                                                                           #
//#  This program is free software: you can redistribute it and/or modify     #
//#  it under the terms of the GNU Affero General Public License as           #
//#  published by the Free Software Foundation, either version 3 of the       #
//#  License, or (at your option) any later version.                          # 
//#                                                                           #
//#  This program is distributed in the hope that it will be useful,          #
//#  but WITHOUT ANY WARRANTY; without even the implied warranty of           #
//#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
//#  GNU Affero General Public License for more details.                      #
//#                                                                           #
//#  You should have received a copy of the GNU Affero General Public License #
//#  along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
//#                                                                           #
//#  IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of    #
//#  this program.  Users of this software do so entirely at their own risk.  #
//#  IMS MAXIMS only ensures the Clinical Safety of unaltered run-time        #
//#  software that it builds, deploys and maintains.                          #
//#                                                                           #
//#############################################################################
//#EOH
// This code was generated by Daniel Laffan using IMS Development Environment (version 1.55 build 2750.16668)
// Copyright (C) 1995-2007 IMS MAXIMS plc. All rights reserved.

package ims.ocrr.forms.noninpatientspecimencollection;

import ims.configuration.gen.ConfigFlag;
import ims.core.patient.vo.PatientRefVo;
import ims.core.vo.MemberOfStaffShortVo;
import ims.core.vo.MemberOfStaffShortVoCollection;
import ims.core.vo.PatientIdCollection;
import ims.core.vo.PersonName;
import ims.core.vo.lookups.PatIdType;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.Control;
import ims.framework.FormName;
import ims.framework.controls.DynamicGridCell;
import ims.framework.controls.DynamicGridCellOptions;
import ims.framework.controls.DynamicGridColumn;
import ims.framework.controls.DynamicGridRow;
import ims.framework.enumerations.Alignment;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.DynamicCellType;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Color;
import ims.framework.utils.Date;
import ims.framework.utils.DateTime;
import ims.framework.utils.Time;
import ims.ocrr.forms.noninpatientspecimencollection.BaseLogic;
import ims.ocrr.forms.noninpatientspecimencollection.GenForm;
import ims.ocrr.forms.noninpatientspecimencollection.GenForm.GroupCollectedEnumeration;
import ims.ocrr.helper.PhlebotomyHelper;
import ims.ocrr.vo.NonInpSpecCollectionSearchCriteriaVo;
import ims.ocrr.vo.OrderedInvestigationStatusVo;
import ims.ocrr.vo.OrderedInvestigationStatusVoCollection;
import ims.ocrr.vo.SpecimenCollectionStatusVo;
import ims.ocrr.vo.SpecimenCollectionStatusVoCollection;
import ims.ocrr.vo.SpecimenWorkListItemListVo;
import ims.ocrr.vo.SpecimenWorkListItemListVoCollection;
import ims.ocrr.vo.lookups.OrderInvStatus;
import ims.ocrr.vo.lookups.PrintStatus;
import ims.ocrr.vo.lookups.SpecimenCollectionMethod;
import ims.ocrr.vo.lookups.SpecimenCollectionStatus;

import java.util.ArrayList;
import java.util.Comparator;

import com.ims.query.builder.client.QueryBuilderClient;
import com.ims.query.builder.client.SeedValue;
import com.ims.query.builder.client.exceptions.QueryBuilderClientException;

public class Logic extends BaseLogic
{
	private static final long serialVersionUID = 1L;

	
	private static final String	PATIENT_COL		= "-1";
	private static final String	PRINT_COL		= "-2";
	private static final String	COLLECTED_COL	= "-3";
	private static final String	DATE_COL		= "-4";
	private static final String	TIME_COL		= "-5";
	private static final String	QUERY_COL		= "-6";
	private static final String	TEXT_COL		= "-7";
	private static final String	INFO_COL		= "-8";
	private static final String	BTN_COL			= "-9";
	
	private static final int LIST_ALL					= 1;
	private static final int LIST_FOR_COLLECTION		= 2;
	private static final int LIST_NOT_COLLECTED			= 3;
	private static final int LIST_COLLECTED				= 4;
	private static final int LIST_COLLECTION_CANCELLED	= 5;
	
	protected void onFormOpen(Object[] args) throws PresentationLogicException
	{
		initialize();
		
		if (form.getGlobalContext().OCRR.getNonInpSpecCollectionSearchCriteriaIsNotNull())
		{
			setSearchCriteria(form.getGlobalContext().OCRR.getNonInpSpecCollectionSearchCriteria());
			populateCollectDataGrid();
			enableContextMenu();
		}
	}
	
	private NonInpSpecCollectionSearchCriteriaVo getSearchCriteria()
	{
		NonInpSpecCollectionSearchCriteriaVo searchCriteria = new NonInpSpecCollectionSearchCriteriaVo();
		
		searchCriteria.setFromDate(form.dteFrom().getValue());
		searchCriteria.setFromTime(form.timFrom().getValue());
		searchCriteria.setToDate(form.dteTo().getValue());
		searchCriteria.setToTime(form.timTo().getValue());
		searchCriteria.setViewType(getViewType());
	
		return searchCriteria;
	}
	
	
	private void setSearchCriteria(NonInpSpecCollectionSearchCriteriaVo nonInpSpecCollectionSearchCriteriaVo)
	{
		setViewType(nonInpSpecCollectionSearchCriteriaVo.getViewType());
		form.dteFrom().setValue(nonInpSpecCollectionSearchCriteriaVo.getFromDate());
		form.timFrom().setValue(nonInpSpecCollectionSearchCriteriaVo.getFromTime());
		form.dteTo().setValue(nonInpSpecCollectionSearchCriteriaVo.getToDate());
		form.timTo().setValue(nonInpSpecCollectionSearchCriteriaVo.getToTime());
	}
	
	private void setViewType(Integer searchType)
	{
		if (searchType == null)
			return;
		
		switch (searchType)
		{
		case LIST_ALL:
			form.GroupCollected().setValue(GroupCollectedEnumeration.rdoAll);
			break;
		case LIST_FOR_COLLECTION:
			form.GroupCollected().setValue(GroupCollectedEnumeration.rdoForCollection);
			break;
		case LIST_NOT_COLLECTED:
			form.GroupCollected().setValue(GroupCollectedEnumeration.rdoOutstanding);
			break;
		case LIST_COLLECTED:
			form.GroupCollected().setValue(GroupCollectedEnumeration.rdoCollected);
			break;
		case LIST_COLLECTION_CANCELLED:
			form.GroupCollected().setValue(GroupCollectedEnumeration.rdoCancelled);
			break;
		}				
	}

	private Integer getViewType()
	{
		GroupCollectedEnumeration searchType = form.GroupCollected().getValue();
		if (GroupCollectedEnumeration.rdoAll.equals(searchType))
		{
			return LIST_ALL;
		}
		if (GroupCollectedEnumeration.rdoForCollection.equals(searchType))
		{
			return LIST_FOR_COLLECTION;
		}
		if (GroupCollectedEnumeration.rdoOutstanding.equals(searchType))
		{
			return LIST_NOT_COLLECTED;
		}
		if (GroupCollectedEnumeration.rdoCollected.equals(searchType))
		{
			return LIST_COLLECTED;
		}
		if (GroupCollectedEnumeration.rdoCancelled.equals(searchType))
		{
			return LIST_COLLECTION_CANCELLED;
		}
		
		return null;
	}
	
	protected void onImbClearClick() throws ims.framework.exceptions.PresentationLogicException
	{
		clearSearchControls();
		form.getGlobalContext().OCRR.setNonInpSpecCollectionSearchCriteria(null); //WDEV-19389 
	}
	protected void onImbSearchClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(checkRequiredAndErrors() == false)
			return;
		
		populateCollectDataGrid();
		form.getGlobalContext().OCRR.setNonInpSpecCollectionSearchCriteria(getSearchCriteria()); //WDEV-19389 
		enableContextMenu();
	}
	private void populateCollectDataGrid()
	{	
		SpecimenWorkListItemListVoCollection voColl = domain.listWorkListItems( getStatus(), getSecondStatus(), form.dteFrom().getValue(), form.timFrom().getValue(), form.dteTo().getValue(), form.timTo().getValue());
		voColl.sort(new EqualDatesNullTimeComparator());
		
		form.dyngrdCollect().getRows().clear();
	
		if(voColl == null || voColl.size() == 0)
		{
			engine.showMessage("No Ward Specimen found");
			return;
		}
		DateTime previousDateTime  = null;
		DynamicGridRow dateTimeRow = null;
		for (int i = 0; i < voColl.size(); i++)
		{
			SpecimenWorkListItemListVo item = voColl.get(i);
			if(item.getSpecimen() == null)
				continue;
			DateTime currentDateTime = new DateTime(item.getDateToCollect(), item.getTimeToCollect());
			if(previousDateTime == null || (currentDateTime != null && !currentDateTime.equals(previousDateTime))) 
			{
				dateTimeRow = form.dyngrdCollect().getRows().newRow();
				previousDateTime = currentDateTime;
			}
			dateTimeRow.setBold(true);
			dateTimeRow.setSelectable(false);
			
			DynamicGridCell dateTimeCell = dateTimeRow.getCells().newCell(getColumn(PATIENT_COL), DynamicCellType.STRING);
			String dateTimeTitle = geDateTimeTitle(item);
			dateTimeCell.setValue(dateTimeTitle);
			dateTimeCell.setTooltip(dateTimeTitle);
			dateTimeCell.setReadOnly(true);
			dateTimeRow.setExpanded(true);
	
			DynamicGridRow patientRow = dateTimeRow.getRows().newRow();
			patientRow.setExpanded(true);
			patientRow.setSelectable(false);
			patientRow.setCollapsedImage(form.getImages().OCRR.Patient);
			patientRow.setExpandedImage(form.getImages().OCRR.Patient);
			patientRow.setIdentifier(getPatientIdentifier(item));
			
			DynamicGridCell patientCell = patientRow.getCells().newCell(getColumn(PATIENT_COL), DynamicCellType.STRING);
			String patientTitle = gePatientTitle(item);
			patientCell.setValue(patientTitle);
			patientCell.setTooltip(patientTitle);
			patientCell.setReadOnly(true);
	
			StringBuffer lastDisciplineCaption = new StringBuffer();
			
			//preappaend specimen source and site if applicable
			if(item.getSpecimen().getSpecimenSourceIsNotNull())
				lastDisciplineCaption.append(item.getSpecimen().getSpecimenSource().getText() + ",");
			if(item.getSpecimen().getSiteCdIsNotNull())
				lastDisciplineCaption.append(item.getSpecimen().getSiteCd().getText() + ",");
			
			String disciplineName = item.getSpecimen().getDisciplineIsNotNull()?item.getSpecimen().getDiscipline().getServiceName():null;
			if(disciplineName == null)
				disciplineName = "(No discipline)";
			lastDisciplineCaption.append(disciplineName);
			lastDisciplineCaption.append(" - ");
	
			for (int j = 0; item.getSpecimen().getInvestigationsIsNotNull() && j < item.getSpecimen().getInvestigations().size(); j++)
			{
				String investigationName = "(No investigation)";
				if(item.getSpecimen().getInvestigations().get(j).getInvestigationIsNotNull() && 
				   item.getSpecimen().getInvestigations().get(j).getInvestigation().getInvestigationIndexIsNotNull() && 
				   item.getSpecimen().getInvestigations().get(j).getInvestigation().getInvestigationIndex().getName() != null)
					investigationName = item.getSpecimen().getInvestigations().get(j).getInvestigation().getInvestigationIndex().getName();
					
				lastDisciplineCaption.append(investigationName);
				lastDisciplineCaption.append(investigationName != "" ? "; " : "");//WDEV-16938
			}
			
			for (int j = 0; item.getSpecimen().getContainersIsNotNull() && j < item.getSpecimen().getContainers().size(); j++)
			{
				if (item.getSpecimen().getContainers().get(j).getContainerQuantity() != 0)//WDEV-16938
				{
					String specimen = "(No specimen)";
					if (item.getSpecimen().getContainers().get(j).getContainerIsNotNull())
						specimen = item.getSpecimen().getContainers().get(j).getContainer().getName();
					lastDisciplineCaption.append(specimen);

					// WDEV-16938
					if (ConfigFlag.UI.OCS_ORDERING_DISPLAY_BLOOD_VOLUMES.getValue() == true && item.getSpecimen().getContainers().get(j).getRequiredVolumeIsNotNull())
					{
						lastDisciplineCaption.append(item.getSpecimen().getContainers().get(j).getRequiredVolume() != 0 ? " - " + item.getSpecimen().getContainers().get(j).getRequiredVolume().toString() + " mls" : " - N/A mls");
					}

					lastDisciplineCaption.append(" (Qty: ");
					lastDisciplineCaption.append(item.getSpecimen().getContainers().get(j).getContainerQuantity());
					lastDisciplineCaption.append("); ");
				}
			}
			
			DynamicGridRow disciplineRow = patientRow.getRows().newRow();
			disciplineRow.setSelectable(true);
			disciplineRow.setCollapsedImage(form.getImages().OCRR.TestTube);
			disciplineRow.setExpandedImage(form.getImages().OCRR.TestTube);
			disciplineRow.setValue(item);
			
			//wdev-2284
			if(item.getCollectionStatusIsNotNull() && (item.getCollectionStatus().equals(SpecimenCollectionStatus.CANCELLED) ||item.getCollectionStatus().equals(SpecimenCollectionStatus.COULDNOTCOLLECT)))
			{
				//Do nothing - no enabled answer box.
			}
			else
			{
				DynamicGridCell collectCell = disciplineRow.getCells().newCell(getColumn(COLLECTED_COL), DynamicCellType.ANSWER);
				setAnswersOptionsToCell(collectCell);
				collectCell.setAutoPostBack(true);
			}
	
			boolean isPatientRowEditable = isRowEditable(item.getCollectionStatus());
			if(isPatientRowEditable == false)
			{
				displayCommonCells(item, disciplineRow);
			}
			else
			{
				//Create comment cell if any comment
				String comment = item.getSpecimenIsNotNull()?item.getSpecimen().getCollectorComment():null;
				if(comment != null && comment.length() > 0)
				{
					DynamicGridCell cellText = disciplineRow.getCells().get(getColumn(TEXT_COL));
					if(cellText != null)
						disciplineRow.getCells().remove(cellText);
					cellText = disciplineRow.getCells().newCell(getColumn(TEXT_COL), DynamicCellType.STRING);
					cellText.setValue(comment);
					cellText.setTooltip(comment);
					cellText.setReadOnly(true);
					setCellMaxLength(item, cellText);
				}
			}
		
			DynamicGridCell printCell = disciplineRow.getCells().newCell(getColumn(PRINT_COL), DynamicCellType.ANSWER);
			boolean isItemPrinted = item.getPrintedIsNotNull() && item.getPrinted().booleanValue();
			loadPrintedStatus(printCell, isItemPrinted);
			if(isItemPrinted)
				printCell.setValue(PrintStatus.PRINTED);
			printCell.setAutoPostBack(true);
						
						
			DynamicGridCell infoCell = disciplineRow.getCells().newCell(getColumn(INFO_COL), DynamicCellType.IMAGE, DynamicGridCellOptions.EDITABLE_DATA_CELL);
			if(item.getSpecimen().getInstructionsToCollectorIsNotNull())
			{
				infoCell.setValue(form.getImages().Core.Information);
				infoCell.setTooltip(PhlebotomyHelper.getInstructorToCollectorTooltip(item.getSpecimen().getInstructionsToCollector()));
			}
			
			DynamicGridCell specimenCell = disciplineRow.getCells().get(getColumn(PATIENT_COL));
			if(specimenCell == null)
				specimenCell = disciplineRow.getCells().newCell(getColumn(PATIENT_COL), DynamicCellType.STRING);
	
			String discipline = lastDisciplineCaption.toString();
			specimenCell.setValue(discipline);
			specimenCell.setReadOnly(true);
			specimenCell.setTooltip(discipline);
		}
	}
	/**
	 * @param item
	 * @param row
	 */
	private void displayCommonCells(SpecimenWorkListItemListVo item, DynamicGridRow row)
	{
		if(item == null || row == null)
			return;
		
		DynamicGridCell statusCell = row.getCells().get(getColumn(COLLECTED_COL));
		if(statusCell != null)
			row.getCells().remove(statusCell);
		statusCell = row.getCells().newCell(getColumn(COLLECTED_COL), DynamicCellType.IMAGE);
		if(item.getCollectionStatusIsNotNull())
		{
			statusCell.setValue(item.getCollectionStatus().getImage());
			statusCell.setTooltip(item.getCollectionStatus().toString());
		}
		
		if(item.getCollectionStatusIsNotNull() && (item.getCollectionStatus().equals(SpecimenCollectionStatus.CANCELLED) ||item.getCollectionStatus().equals(SpecimenCollectionStatus.COULDNOTCOLLECT)))
		{
			createControlsForNotCollection(row, item);
		}
		else
		{
			Date date = null;
			Time time = null;
			if(item.getSpecimenIsNotNull() && item.getSpecimen().getCollDateTimePlacerIsNotNull())
			{
				date = item.getSpecimen().getCollDateTimePlacer().getDate();
				time = item.getSpecimen().getCollDateTimePlacer().getTime();
			}
			
			DynamicGridCell cellDate = row.getCells().get(getColumn(DATE_COL));
			if(cellDate != null)
				row.getCells().remove(cellDate);
			cellDate = row.getCells().newCell(getColumn(DATE_COL), DynamicCellType.STRING, DynamicGridCellOptions.READ_ONLY_DATA_CELL);
			cellDate.setValue(date != null?date.toString():"");
			cellDate.setReadOnly(true);
			
			DynamicGridCell cellTime = row.getCells().get(getColumn(TIME_COL));
			if(cellTime != null)
				row.getCells().remove(cellTime);
			cellTime = row.getCells().newCell(getColumn(TIME_COL), DynamicCellType.STRING, DynamicGridCellOptions.READ_ONLY_DATA_CELL);
			cellTime.setValue(time != null?time.toString():"");
			cellTime.setReadOnly(true);
			
			DynamicGridCell cellQuery = row.getCells().get(getColumn(QUERY_COL));
			if(cellQuery != null)
				row.getCells().remove(cellQuery);
			cellQuery = row.getCells().newCell(getColumn(QUERY_COL), DynamicCellType.STRING, DynamicGridCellOptions.READ_ONLY_DATA_CELL);
			cellQuery.setValue(item.getSpecimen().getCollectingMosIsNotNull() && item.getSpecimen().getCollectingMos().getNameIsNotNull()?item.getSpecimen().getCollectingMos().getName().toString():"");
			cellQuery.setReadOnly(true);
			
			DynamicGridCell cellText = row.getCells().get(getColumn(TEXT_COL));
			if(cellText != null)
				row.getCells().remove(cellText);
			cellText = row.getCells().newCell(getColumn(TEXT_COL), DynamicCellType.STRING, DynamicGridCellOptions.READ_ONLY_DATA_CELL);
			cellText.setValue(item.getSpecimen().getCollectorComment());
			cellText.setTooltip(item.getSpecimen().getCollectorComment());
			cellText.setReadOnly(true);
			setCellMaxLength(item, cellText);
		}
		
		//row.setReadOnly(true);
		row.setBackColor(Color.LightGray);
	}
	
	private String gePatientTitle(SpecimenWorkListItemListVo item)
	{
		StringBuffer sb = new StringBuffer();
		String patient = "(No patient)";
		if(item.getSpecimen().getOrderIsNotNull() &&
			item.getSpecimen().getOrder().getPatientIsNotNull() &&
			item.getSpecimen().getOrder().getPatient().getNameIsNotNull())
			patient = item.getSpecimen().getOrder().getPatient().getName().toString();
	
		sb.append(patient);
		sb.append(" - ");
		sb.append(getIdentifier(item));
		return sb.toString();
	}
	
	private PatientRefVo getPatientIdentifier(SpecimenWorkListItemListVo item)
	{
		if(item.getSpecimen().getOrderIsNotNull() &&
			item.getSpecimen().getOrder().getPatientIsNotNull())
			return item.getSpecimen().getOrder().getPatient();
		return null;
	}
	
	private String geDateTimeTitle(SpecimenWorkListItemListVo item)
	{
		StringBuffer sb = new StringBuffer();
		sb.append(item.getTimeToCollectIsNotNull()?item.getTimeToCollect().toString():"(No Time)");
		sb.append(" - ");
		sb.append(item.getDateToCollectIsNotNull()?item.getDateToCollect().toString():"(No Date)");
		return sb.toString();
	}
	
	private Object getIdentifier(SpecimenWorkListItemListVo item)
	{
		String patIdValue = "";
		String patIdentifier = ConfigFlag.UI.DISPLAY_PATID_TYPE.getValue();
		PatIdType patIdType = PatIdType.getNegativeInstance(patIdentifier);
		if(patIdType != null)
		{
			PatientIdCollection patIdsColl = null;
			if(item.getSpecimen().getOrderIsNotNull() &&
					item.getSpecimen().getOrder().getPatientIsNotNull())
				patIdsColl = item.getSpecimen().getOrder().getPatient().getIdentifiers();
			for (int i = 0; patIdsColl != null && i < patIdsColl.size(); i++)
			{
				if(patIdsColl.get(i).getTypeIsNotNull() && patIdsColl.get(i).getType().equals(patIdType))
				{
					patIdValue = patIdsColl.get(i).getValue();
					break;
				}
			}
		}
		
		return patIdType.toString() + " " + patIdValue;
	}
	private SpecimenCollectionStatus getStatus()
	{
		GroupCollectedEnumeration collEnum = form.GroupCollected().getValue();
		if(collEnum != null)
		{
			if(collEnum.equals(GroupCollectedEnumeration.rdoCancelled))
				return SpecimenCollectionStatus.CANCELLED;
			
			if(collEnum.equals(GroupCollectedEnumeration.rdoOutstanding))
				return SpecimenCollectionStatus.PHLEBCOULDNOTCOLLECT;
			
			if(collEnum.equals(GroupCollectedEnumeration.rdoCollected))
				return SpecimenCollectionStatus.COLLECTIONCOMPLETE;
			
			if(collEnum.equals(GroupCollectedEnumeration.rdoForCollection))
			{	
				return SpecimenCollectionStatus.FORCOLLECTION;
			}
		}
		
		return null;
	}
	
	private SpecimenCollectionStatus getSecondStatus()
	{
		GroupCollectedEnumeration collEnum = form.GroupCollected().getValue();
		if(collEnum != null)
		{
			if(collEnum.equals(GroupCollectedEnumeration.rdoForCollection))
			{	
				return SpecimenCollectionStatus.PHLEBCOULDNOTCOLLECT;
			}
		}
		
		return null;
	}
	
	public void initialize()
	{
		form.GroupCollected().setValue(GroupCollectedEnumeration.rdoAll);
		setDefaultTimes();
		setDynamicGridColumns();
	}
	
	private void setDynamicGridColumns()
	{
		DynamicGridColumn column = form.dyngrdCollect().getColumns().newColumn("Collection Time Date / Patient ", PATIENT_COL);
		column.setWidth(275);
		column.setCanGrow(true);
	
		column = form.dyngrdCollect().getColumns().newColumn("Info", INFO_COL);
		column.setWidth(40);
		column.setAlignment(Alignment.CENTER);
		
		column = form.dyngrdCollect().getColumns().newColumn("Print", PRINT_COL);
		column.setWidth(30);
		column.setAlignment(Alignment.CENTER);
	
		column = form.dyngrdCollect().getColumns().newColumn("Collected", COLLECTED_COL);
		column.setWidth(60);
		column.setAlignment(Alignment.CENTER);
	
		column = form.dyngrdCollect().getColumns().newColumn("Date", DATE_COL);
		column.setWidth(80);
	
		column = form.dyngrdCollect().getColumns().newColumn("Time", TIME_COL);
		column.setWidth(40);
	
		column = form.dyngrdCollect().getColumns().newColumn("Collector", QUERY_COL);
		column.setWidth(100);
	
		column = form.dyngrdCollect().getColumns().newColumn("Collector's Comments", TEXT_COL);
		column.setWidth(135);
		
		column = form.dyngrdCollect().getColumns().newColumn("Save", BTN_COL);
		column.setAlignment(Alignment.CENTER);
		column.setWidth(-1);
	}
	
	private void setDefaultTimes()
	{
		DateTime fromDate = new DateTime();
		DateTime toDate   = new DateTime();
		fromDate.addHours(-6);
		toDate.addHours(6);
		
		form.dteFrom().setValue(fromDate.getDate());
		form.timFrom().setValue(fromDate.getTime());
	
		form.dteTo().setValue(toDate.getDate());
		form.timTo().setValue(toDate.getTime());
	}
	
	private void clearSearchControls()
	{
		form.dteFrom().setValue(null);
		form.dteTo().setValue(null);
		form.timFrom().setValue(null);
		form.timTo().setValue(null);
		form.dyngrdCollect().getRows().clear();
	}
	
	private boolean checkRequiredAndErrors()
	{
		ArrayList errors = new ArrayList();
		
		Date fromDate = form.dteFrom().getValue();
		if(fromDate == null)
			errors.add("'From Date' is mandatory");
		
		Date toDate = form.dteTo().getValue();
		if(toDate == null)
			errors.add("'To Date' is mandatory");
		
		if(fromDate != null && toDate != null)////WDEV-15247
		{
			DateTime fromDateTime = new DateTime(form.dteFrom().getValue(), form.timFrom().getValue());
			DateTime toDateTime   = new DateTime(form.dteTo().getValue(), form.timTo().getValue());
			if(fromDateTime != null && toDateTime != null)//WDEV-15247
			{
				if(fromDateTime.isGreaterThan(toDateTime))
				{
					errors.add("Invalid Date Range Search: 'From Date Time' should be before 'To Date Time'");
				}
			}
		}
		
		if(errors.size() > 0)
		{
			String[] searchErrors = new String[errors.size()];
			errors.toArray(searchErrors);
			engine.showErrors("Invalid Search Criteria", searchErrors);
			return false;
		}
		
		return true;
	}
	protected void onDyngrdCollectCellTextSubmited(DynamicGridCell cell)
	{
		if (cell.getColumn().equals(getColumn(QUERY_COL)))
		{
			cell.getItems().clear();
			String value = cell.getTypedText();
			PersonName name = new PersonName();
			MemberOfStaffShortVo filter = new MemberOfStaffShortVo();
			name.setSurname(value);
			filter.setIsActive(Boolean.TRUE);
			filter.setName(name);
			MemberOfStaffShortVoCollection voColl = domain.listMembersOfStaff(filter);
			for (int i = 0; i < voColl.size(); i++)
			{
				cell.getItems().newItem(voColl.get(i));
			}
			int cellItemSize = cell.getItems().size();
			if (cellItemSize > 0)
			{
				if (cellItemSize == 1)
					cell.setValue(cell.getItems().get(0));
				cell.showOpened();
			}
		}
	}
	protected void onDyngrdCollectCellButtonClicked(DynamicGridCell cell)
	{
		save(cell);
	}
	private boolean save(DynamicGridCell cell)
	{
		DynamicGridRow row = cell.getRow();

		Object obj = row.getValue();
		if (obj instanceof SpecimenWorkListItemListVo)
		{
			SpecimenCollectionStatus answer = (SpecimenCollectionStatus) row.getCells().get(getColumn(COLLECTED_COL)).getValue();
			if (answer == null)
			{
				engine.showErrors(new String[]{"Please select Collected"});
				return false;
			}
			MemberOfStaffShortVo phlebotomist = null;
			DateTime dateTimeCollected 		= null;
			String commentCollected			= null;
			
			boolean isCollected = answer.equals(SpecimenCollectionStatus.COLLECTIONCOMPLETE);
			if (isCollected)
			{
				Date dateCollected = (Date) row.getCells().get(getColumn(DATE_COL)).getValue();
				Time timeCollected = (Time) row.getCells().get(getColumn(TIME_COL)).getValue();
				Object mosObj = row.getCells().get(getColumn(QUERY_COL)).getValue();
				phlebotomist = mosObj instanceof MemberOfStaffShortVo ? (MemberOfStaffShortVo) mosObj : null;
				commentCollected = (String) row.getCells().get(getColumn(TEXT_COL)).getValue();

				ArrayList errors = new ArrayList();
				if (dateCollected == null)
					errors.add("Date is mandatory");
				if (timeCollected == null)
					errors.add("Time is mandatory");
				if (phlebotomist == null)
					errors.add("Phlebotomist is mandatory");
				errors.trimToSize();

				if (errors.size() > 0)
				{
					String[] uiErrors = new String[errors.size()];
					errors.toArray(uiErrors);
					engine.showErrors(uiErrors);
					return false;
				}

				dateTimeCollected = new DateTime(dateCollected, timeCollected);
			}
			
			boolean isNotColleted = answer.equals(SpecimenCollectionStatus.CANCELLED);
			if(isNotColleted)
			{
				commentCollected = (String) row.getCells().get(getColumn(TEXT_COL)).getValue();
				if (commentCollected == null || commentCollected.length() == 0)
				{
					engine.showErrors(new String[]{"Comment is mandatory"});
					return false;
				}
			}

			SpecimenWorkListItemListVo voSpecimenWorkListItemList = (SpecimenWorkListItemListVo) obj;
			if (voSpecimenWorkListItemList != null)
			{
				String reason = commentCollected;
				if (isCollected)
				{
					voSpecimenWorkListItemList.getSpecimen().setCollDateTimePlacer(dateTimeCollected);
					voSpecimenWorkListItemList.getSpecimen().setCollectingMos(phlebotomist);
					voSpecimenWorkListItemList.getSpecimen().setIsAwaitingCollection(Boolean.FALSE);
					voSpecimenWorkListItemList.setCollectionStatus(SpecimenCollectionStatus.COLLECTIONCOMPLETE);
					
					String existingComment 	  = voSpecimenWorkListItemList.getSpecimen().getCollectorComment();
					String phlebotomistString = phlebotomist != null ? phlebotomist.getInitials() : null;  
					commentCollected = getPhlebotomistComment(existingComment, phlebotomistString, dateTimeCollected, commentCollected);
					//WDEV-2958 - don't add new comment if exceeds the max allowed value
					if(getMaxLength(existingComment) < 0)
						commentCollected = existingComment;
				}
				else
				{
					voSpecimenWorkListItemList.setCollectionStatus(SpecimenCollectionStatus.CANCELLED);
					String existingComment 	  = voSpecimenWorkListItemList.getSpecimen().getCollectorComment();
					DateTime date = new DateTime();
					String userRealName = engine.getLoggedInUser().getUserRealName();
					commentCollected = getPhlebotomistComment(existingComment, userRealName, date, commentCollected);
					//WDEV-2958 - don't add new comment if exceeds the max allowed value
					if(getMaxLength(existingComment) < 0)
						commentCollected = existingComment;
					
					//WDEV-3000 - On the Cancellation set the IsAwaiting to False in the OrderSpecimen for the selected investigation.
					voSpecimenWorkListItemList.getSpecimen().setIsAwaitingCollection(Boolean.FALSE);
					
					//WDEV-2570 - Status of specimens cancelled on the Ward Collection screen should be set to "Cancelled"
					for (int i = 0; i < voSpecimenWorkListItemList.getSpecimen().getInvestigations().size(); i++)
					{
						OrderedInvestigationStatusVo  orderedInvestigationStatusVo = voSpecimenWorkListItemList.getSpecimen().getInvestigations().get(i).getOrdInvCurrentStatus();
						if(orderedInvestigationStatusVo == null)
							orderedInvestigationStatusVo = new OrderedInvestigationStatusVo();
						orderedInvestigationStatusVo.setChangeDateTime(date);
						orderedInvestigationStatusVo.setProcessedDateTime(new DateTime());
						orderedInvestigationStatusVo.setOrdInvStatus(OrderInvStatus.CANCELLED);
						orderedInvestigationStatusVo.setChangeUser(userRealName);
						orderedInvestigationStatusVo.setStatusReason(reason);
						voSpecimenWorkListItemList.getSpecimen().getInvestigations().get(i).setOrdInvCurrentStatus(orderedInvestigationStatusVo);
						//Add Status to History
						if (voSpecimenWorkListItemList.getSpecimen().getInvestigations().get(i).getOrdInvStatusHistory() == null)
							voSpecimenWorkListItemList.getSpecimen().getInvestigations().get(i).setOrdInvStatusHistory(new OrderedInvestigationStatusVoCollection());
						voSpecimenWorkListItemList.getSpecimen().getInvestigations().get(i).getOrdInvStatusHistory().add(orderedInvestigationStatusVo);
					}
				}
				if(voSpecimenWorkListItemList.getSpecimen().getSpecimenCollectionStatus() == null)
					voSpecimenWorkListItemList.getSpecimen().setSpecimenCollectionStatus(new SpecimenCollectionStatusVoCollection());

				//WDEV-2570 - Create a new SpecimenCollectionStatusVo
				SpecimenCollectionStatusVo voSCSVo = new SpecimenCollectionStatusVo();
				voSCSVo.setCollectionStatus(voSpecimenWorkListItemList.getCollectionStatus());
				voSCSVo.setListType(SpecimenCollectionMethod.WARDCOLLECTION);
				voSCSVo.setReason(reason);
				voSpecimenWorkListItemList.getSpecimen().getSpecimenCollectionStatus().add(voSCSVo);
				
				voSpecimenWorkListItemList.getSpecimen().setCollectorComment(getHelper().getCollectorCommentTrimmed(commentCollected));
				
				try
				{
					voSpecimenWorkListItemList = domain.saveWorkListItem(voSpecimenWorkListItemList);
				}
				catch (StaleObjectException e)
				{
					engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
					populateCollectDataGrid();
				}
				
				row.setValue(voSpecimenWorkListItemList);
				row.setBackColor(Color.LightGray);
				removeCommonCells(row);
				displayCommonCells(voSpecimenWorkListItemList, row);
				enableContextMenu();
			}
		}
		return true;
	}
	
	private String getPhlebotomistComment(String existingComment, String phlebotomistString, DateTime dateTimeCollected, String commentCollected)
	{
		return new ims.ocrr.helper.PhlebotomyHelper().getPhlebotomistComment(existingComment, phlebotomistString, dateTimeCollected, commentCollected);
	}
	protected void onDyngrdCollectCellValueChanged(DynamicGridCell cell)
	{
		processCellPostback(cell);
	}
	
	private void processCellPostback(DynamicGridCell cell)
	{
		Object rowValue  = cell.getRow().getValue();
		Object cellValue = cell.getRow().getCells().get(getColumn(PRINT_COL)).getValue();
		boolean isRowEditable = false;
		if(rowValue instanceof SpecimenWorkListItemListVo)
		{
			isRowEditable = isRowEditable(((SpecimenWorkListItemListVo)rowValue).getCollectionStatus());
		}
		//wdev-2284
	//			boolean isForPrinted = cellValue != null && cellValue.equals(PrintStatus.FORPRINTING); 
	//			boolean isPrinted 	 = cellValue != null && cellValue.equals(PrintStatus.PRINTED);
				
		if (isRowEditable)
		{
		//wdev-2284
		//	if(isForPrinted || isPrinted)
		//	{
		//		DynamicGridCell collectedCell = cell.getRow().getCells().get(getColumn(COLLECTED_COL));
		//		// Create Collected Cell
		//		if (collectedCell == null)
		//		{
		//			collectedCell = cell.getRow().getCells().newCell(getColumn(COLLECTED_COL), DynamicCellType.ANSWER);
		//			setAnswersOptionsToCell(collectedCell);
		//			collectedCell.setAutoPostBack(true);
		//		}
	
				if (cell.getColumn().equals(getColumn(COLLECTED_COL)))
				{
					if (cell.getValue() != null)
					{
						if (cell.getValue().equals(SpecimenCollectionStatus.COLLECTIONCOMPLETE))
						{
							createControlsForCollection(cell.getRow());
						}
						if (cell.getValue().equals(SpecimenCollectionStatus.CANCELLED))
						{
							createControlsForNotCollection(cell.getRow());
						}
						createCommonCells(cell.getRow());
					}
					else
					{
						clearAllCells(cell.getRow());
					}
				}
		//wdev-2284
		//	}
		//	else
		//	{
		//		removeCellByColumn(cell.getRow(), COLLECTED_COL);
		//		clearAllCells(cell.getRow());
		//	}
		}
		
		//enablePrintButton(isForPrinted || isAtLeastOneRecordToPrint());
		
	}
	
	private boolean isRowEditable(SpecimenCollectionStatus type)
	{
		return type != null && (type.equals(SpecimenCollectionStatus.FORCOLLECTION) || type.equals(SpecimenCollectionStatus.PHLEBCOULDNOTCOLLECT));
	}
	
	private void createCommonCells(DynamicGridRow row)
	{
		if(row.getCells().get(getColumn(BTN_COL)) == null)
		{
			DynamicGridCell cell = row.getCells().newCell(getColumn(BTN_COL), DynamicCellType.IMAGEBUTTON, DynamicGridCellOptions.EDITABLE_DATA_CELL);
			cell.setValue(form.getImages().OCRR.SaveGrid);
			cell.setTooltip("Save");
		}
	}
	
	private void createControlsForNotCollection(DynamicGridRow row)
	{
		createControlsForNotCollection(row, null);
	}
	private void createControlsForNotCollection(DynamicGridRow row, SpecimenWorkListItemListVo item)
	{
		clearVariableCells(row);
	
		DynamicGridCell cell = row.getCells().newCell(getColumn(DATE_COL), DynamicCellType.LABEL, DynamicGridCellOptions.READ_ONLY_DATA_CELL);
		cell = row.getCells().newCell(getColumn(TIME_COL), DynamicCellType.LABEL, DynamicGridCellOptions.READ_ONLY_DATA_CELL);
		cell = row.getCells().newCell(getColumn(QUERY_COL), DynamicCellType.LABEL, DynamicGridCellOptions.LABEL_CELL);
		getColumn(QUERY_COL).setAlignment(Alignment.RIGHT);
		cell.setValue("Reason:");
		cell = row.getCells().newCell(getColumn(TEXT_COL), DynamicCellType.STRING, item !=null?DynamicGridCellOptions.READ_ONLY_DATA_CELL:DynamicGridCellOptions.EDITABLE_DATA_CELL);
		setCellMaxLength(item, cell);
		if(item != null)
		{
			if(item.getSpecimenIsNotNull() && item.getSpecimen().getCollectorCommentIsNotNull())
			{
				cell.setValue(item.getSpecimen().getCollectorComment());
				cell.setTooltip(item.getSpecimen().getCollectorComment());
			}
		}
	}
	
	private void createControlsForCollection(DynamicGridRow row)
	{
		clearVariableCells(row);
		DynamicGridCell cell = row.getCells().newCell(getColumn(DATE_COL), DynamicCellType.DATE, DynamicGridCellOptions.EDITABLE_DATA_CELL);
		setDefaultDateValue(cell);
		cell = row.getCells().newCell(getColumn(TIME_COL), DynamicCellType.TIME, DynamicGridCellOptions.EDITABLE_DATA_CELL);
		setDefaultTimeValue(cell);
		cell = row.getCells().newCell(getColumn(QUERY_COL), DynamicCellType.QUERYCOMBOBOX, DynamicGridCellOptions.EDITABLE_DATA_CELL);
		getColumn(QUERY_COL).setAlignment(Alignment.LEFT);
		cell.setAutoPostBack(true);
		setDefaultMosValue(cell);
		cell = row.getCells().newCell(getColumn(TEXT_COL), DynamicCellType.STRING, DynamicGridCellOptions.EDITABLE_DATA_CELL);
		setCellMaxLength(((row.getValue() instanceof SpecimenWorkListItemListVo)?((SpecimenWorkListItemListVo)row.getValue()):null), cell);
	}
	
	private void setDefaultDateValue(DynamicGridCell cell)
	{
		cell.setValue(new Date());
	}
	
	private void setDefaultTimeValue(DynamicGridCell cell)
	{
		DynamicGridRow parentRow = cell.getRow().getParent();
		//Get Previous row time and set it to the current row
		for (int i = 0; parentRow != null && i < parentRow.getRows().size(); i++)
		{
			if(i > 0 && parentRow.getRows().get(i).getValue().equals(cell.getRow().getValue()))
			{
				DynamicGridColumn column = getColumn(TIME_COL);
				if(column != null)
				{
					DynamicGridCell timCell = parentRow.getRows().get(i-1).getCells().get(column);
					if(timCell != null)
					{
						Object previousTime = timCell.getValue();
						if(previousTime instanceof Time)
							cell.setValue(previousTime); 
					}
				}
				
				break;
			}
		}
	}
	
	private void setDefaultMosValue(DynamicGridCell cell)
	{
		MemberOfStaffShortVo mos = (MemberOfStaffShortVo)domain.getMosUser();
		if (mos != null && mos.getNameIsNotNull())
		{
			cell.getItems().newItem(mos);
			cell.setValue(mos);
		}		
	}
	
	private void clearVariableCells(DynamicGridRow row)
	{
		removeCellByColumn(row, DATE_COL);
		removeCellByColumn(row, TIME_COL);
		removeCellByColumn(row, QUERY_COL);
		removeCellByColumn(row, TEXT_COL);
	}
	
	private void removeCommonCells(DynamicGridRow row)
	{
		removeCellByColumn(row, BTN_COL);
	}
	
	private void clearAllCells(DynamicGridRow row)
	{
		clearVariableCells(row);
		removeCommonCells(row);
	}
	
	private void removeCellByColumn(DynamicGridRow row, String colIdentifier)
	{
		DynamicGridCell cell;
		cell = row.getCells().get(getColumn(colIdentifier));
		if (cell != null)
			row.getCells().remove(cell);
	}
	
	private void setAnswersOptionsToCell(DynamicGridCell cell)
	{
		if (cell == null)
			return;
	
		cell.getItems().newItem(SpecimenCollectionStatus.COLLECTIONCOMPLETE);
		cell.getItems().newItem(SpecimenCollectionStatus.CANCELLED);
	}
	private DynamicGridColumn getColumn(String identifier)
	{
		return form.dyngrdCollect().getColumns().getByIdentifier(identifier);
	}
	
	private void loadPrintedStatus(DynamicGridCell cell, boolean isPrinted)
	{
		if(cell == null)
			return;
		cell.getItems().clear();
		cell.getItems().newItem(PrintStatus.FORPRINTING);
		if(isPrinted)
			cell.getItems().newItem(PrintStatus.PRINTED);
	}
	
	//WDEV-1590 - display the records having time = null (No time) at the end
	class EqualDatesNullTimeComparator implements Comparator
	{
		public int compare(Object arg0, Object arg1)
		{
			final int EQUAL  = 0;
			final int AFTER  = 1;
		    
			SpecimenWorkListItemListVo voObj1 = (SpecimenWorkListItemListVo) arg0;
			SpecimenWorkListItemListVo voObj2 = (SpecimenWorkListItemListVo) arg1;
			Date startDateToCollect = voObj1.getDateToCollect();
			Date endDateToCollect 	= voObj2.getDateToCollect();
			Time startTimeToCollect = voObj1.getTimeToCollect();
			Time endTimeToCollect 	= voObj2.getTimeToCollect();
	
			if(startDateToCollect != null && endDateToCollect != null)
			{
				//Covers only equal dates and null time (Date Time sort moved into hql query)
				if(startDateToCollect.equals(endDateToCollect))
				{
					if(startTimeToCollect == null && endTimeToCollect != null)
					{
						return AFTER;
					}
				}
			}
	
			return EQUAL;
		}
	}
	
	protected void onContextMenuItemClick(int menuItemID, Control sender) throws PresentationLogicException
	{
		switch(menuItemID)
		{
			case GenForm.ContextMenus.OutpatientPhlebotomy.MoveToPhlebotomy:
				 moveToPhlebotomy();
			break;
		}
	}
	private void moveToPhlebotomy()
	{
		Object value = form.dyngrdCollect().getValue();
		if(value instanceof SpecimenWorkListItemListVo)
		{
			form.getGlobalContext().OCRR.setSpecimenWorkListItemList((SpecimenWorkListItemListVo)value);
			engine.open(form.getForms().OCRR.WardSpecimenMoveTo);			
		}	
	}
	protected void onDyngrdCollectRowSelectionChanged(DynamicGridRow row)
	{
		enableContextMenu();
		setSelectedPatientIntoContext();
	}
	
	private void enableContextMenu()
	{
		boolean isRowEditable = false;
		boolean isAtLeastOneActivePhlebMayCollect = false;
		DynamicGridRow row = form.dyngrdCollect().getSelectedRow();
		if(specimenSelected(row))
		{
			SpecimenWorkListItemListVo specimenWorkListItemListVo = ((SpecimenWorkListItemListVo)row.getValue());
			isRowEditable = isRowEditable(specimenWorkListItemListVo.getCollectionStatus());
			Boolean isAtLeasOneActive = domain.isAtLeastOneActivePhlebMayCollect(specimenWorkListItemListVo);
			isAtLeastOneActivePhlebMayCollect = isAtLeasOneActive != null? isAtLeasOneActive.booleanValue():false; 
		}
		
		form.getContextMenus().getOutpatientPhlebotomyMoveToPhlebotomyItem().setVisible(isRowEditable && isAtLeastOneActivePhlebMayCollect);
	}
	
	protected void onBtnPrintClick() throws PresentationLogicException
	{
		form.getLocalContext().setContextDummyForReportsLabel(null);
		form.getLocalContext().setContextDummyForReportsScreen(null);
		
		if(form.dyngrdCollect().getRows().size() == 0)
		{
			engine.showMessage("There is no data to print");
			return;
		}
		
		SpecimenWorkListItemListVoCollection voColl = getWorkListItemsToprint();
		if(voColl != null && voColl.size() != 0)
		{			
			SpecimenWorkListItemListVo dummy = new SpecimenWorkListItemListVo();
			dummy.setID_SpecimenWorkListItem(new Integer(-1));
			form.getLocalContext().setContextDummyForReportsLabel(dummy);
		}
		
		form.getGlobalContext().Core.setPrepareForPrinting(Boolean.TRUE);
		engine.open(form.getForms().Core.PrintReport);		
	}
	
	private SpecimenWorkListItemListVoCollection getWorkListItemsToprint()
	{
		SpecimenWorkListItemListVoCollection voColl = new SpecimenWorkListItemListVoCollection();
		for (int i = 0; i < form.dyngrdCollect().getRows().size(); i++)
		{
			for (int j = 0; j < form.dyngrdCollect().getRows().get(i).getRows().size(); j++)
			{
				for (int k = 0; k < form.dyngrdCollect().getRows().get(i).getRows().get(j).getRows().size(); k++)
				{
					 DynamicGridCell printCell = form.dyngrdCollect().getRows().get(i).getRows().get(j).getRows().get(k).getCells().get(getColumn(PRINT_COL));
					 if(printCell != null && printCell.getValue() != null && printCell.getValue().equals(PrintStatus.FORPRINTING))
					 {
						 voColl.add((SpecimenWorkListItemListVo) form.dyngrdCollect().getRows().get(i).getRows().get(j).getRows().get(k).getValue());
					 }
				}
			}
		}
		
		return voColl;
	}
	
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if(formName.equals(form.getForms().Core.PrintReport) && result.equals(DialogResult.OK))
		{
			printSelectedItems();
		}
		if(formName.equals(form.getForms().OCRR.WardSpecimenMoveTo))
		{
			if(result.equals(DialogResult.OK))
			{
				refreshRecord(form.getGlobalContext().OCRR.getSpecimenWorkListItemList());
				enableContextMenu();
			}
			form.getGlobalContext().OCRR.setSpecimenWorkListItemList(null);
		}
	}
	
	private void printSelectedItems()
	{
		String urlQueryServer = ConfigFlag.GEN.QUERY_SERVER_URL.getValue();
		String urlReportServer = ConfigFlag.GEN.REPORT_SERVER_URL.getValue();
	
		SpecimenWorkListItemListVoCollection voColl = getWorkListItemsToprint(); 
		
		if(voColl.size() == 0)
		{
			//print screen
			QueryBuilderClient client = new QueryBuilderClient(urlQueryServer, engine.getSessionId());
	
			client.addSeed(new SeedValue("METHOD", new Integer(SpecimenCollectionMethod.WARDCOLLECTION.getID()), Integer.class));
			SpecimenCollectionStatus status = getStatus();
			client.addSeed(new SeedValue("STATUS", (status == null ? null : new Integer(status.getId())), Integer.class));
			SpecimenCollectionStatus secondStatus = getSecondStatus();
			client.addSeed(new SeedValue("STATUS2", (secondStatus == null ? null : new Integer(secondStatus.getId())), Integer.class));
			client.addSeed(new SeedValue("DATE1", form.dteFrom().getValue().getDate(), java.util.Date.class));
			client.addSeed(new SeedValue("TIME1", (form.timFrom().getValue() != null ? form.timFrom().getValue().toString() : null), String.class));
			client.addSeed(new SeedValue("DATE2", form.dteTo().getValue().getDate(), java.util.Date.class));
			client.addSeed(new SeedValue("TIME2", (form.timTo().getValue() != null ? form.timTo().getValue().toString() : null), String.class));
			
			try
			{
				client.printReport(form.getGlobalContext().Core.getReport(), form.getGlobalContext().Core.getTemplate(), urlReportServer, form.getGlobalContext().Core.getPrinterSelect(), 1);
			} 
			catch (QueryBuilderClientException e1)
			{
				engine.showMessage("Error creating report: " + e1.getMessage());
				return;
			}
			
		}
		else
		{
			for (int i = 0; i < voColl.size(); i++)
			{
				QueryBuilderClient client = new QueryBuilderClient(urlQueryServer, engine.getSessionId());
	
				client.addSeed(new SeedValue("SpecimenWorkListItem_id", voColl.get(i).getID_SpecimenWorkListItem(), Integer.class));
				
				try
				{
					client.printReport(form.getGlobalContext().Core.getReport(), form.getGlobalContext().Core.getTemplate(), urlReportServer, form.getGlobalContext().Core.getPrinterSelect(), 1);
				} 
				catch (QueryBuilderClientException e1)
				{
					engine.showMessage("Error creating report: " + e1.getMessage());
					return;
				}
			}			
			
			refreshDataInGrid(voColl);
		}
		
	}
	private void refreshRecord(SpecimenWorkListItemListVo specimenWorkListItemList)
	{
		if(specimenWorkListItemList != null && specimenWorkListItemList.getCollectionStatus().equals(SpecimenCollectionStatus.MOVEDTOPHLEBOTOMY))
		{
			DynamicGridRow row = form.dyngrdCollect().getSelectedRow();
			if(row != null)
			{
				//WDEV-2990 - clear existing cell and then set the value to the selected row 
				clearVariableCells(row);
				removeCommonCells(row);
				displayCommonCells(specimenWorkListItemList, row);
				row.setValue(specimenWorkListItemList);
			}
		}
	}
	
	private void refreshDataInGrid(SpecimenWorkListItemListVoCollection voColl)
	{
		for (int i = 0; i < form.dyngrdCollect().getRows().size(); i++)
		{
			for (int j = 0; j < form.dyngrdCollect().getRows().get(i).getRows().size(); j++)
			{
				for (int k = 0; k < form.dyngrdCollect().getRows().get(i).getRows().get(j).getRows().size(); k++)
				{
					DynamicGridRow row = form.dyngrdCollect().getRows().get(i).getRows().get(j).getRows().get(k);
					DynamicGridCell printCell = row.getCells().get(getColumn(PRINT_COL));
					if(printCell != null && printCell.getValue() != null && printCell.getValue().equals(PrintStatus.FORPRINTING))
					{
						loadPrintedStatus(printCell, true);
						printCell.setValue(PrintStatus.PRINTED);
						//Set the value of the row with a new one (otherwise will get a Stale Object Exception when saving)
						SpecimenWorkListItemListVo voNewSavedValue = getNewValueFromSavedList(row.getValue(), voColl);
						if(voNewSavedValue != null)
							row.setValue(voNewSavedValue);
					}
				}
			}
		}
	}
	private SpecimenWorkListItemListVo getNewValueFromSavedList(Object value, SpecimenWorkListItemListVoCollection voColl)
	{
		if(value == null)
			return null;
		for (int i = 0; i < voColl.size(); i++)
		{
			if(voColl.get(i).equals(value))
			{
				return voColl.get(i);
			}
		}
		
		return null;
	}

	private void setSelectedPatientIntoContext()
	{
		DynamicGridRow row = form.dyngrdCollect().getSelectedRow();
		if(specimenSelected(row))
		{
			if(row.getParent() != null && row.getParent().getIdentifier() instanceof PatientRefVo)
			{
				form.getGlobalContext().Core.setPatientShort(domain.getPatient((PatientRefVo)row.getParent().getIdentifier()));
			}
		}
	}
	private boolean specimenSelected(DynamicGridRow row)
	{
		return row != null && row.getValue() instanceof SpecimenWorkListItemListVo;
	}
	
	//calculate dynamically the max length of the comment based on what you can expect when saving the colector comment.
	private int getMaxLength(String collectorComment)
	{
		return getHelper().getMaxLength(collectorComment);
	}

	private void setCellMaxLength(SpecimenWorkListItemListVo item, DynamicGridCell cellText)
	{
		String collectorComment = item != null ? item.getSpecimen().getCollectorComment() : "";
		getHelper().setCellMaxLength(collectorComment, cellText);
	}
	
	private PhlebotomyHelper getHelper()
	{
		return new PhlebotomyHelper(engine.getLoggedInUser().getUserRealName());
	}
}
