//#############################################################################
//#                                                                           #
//#  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 Gabriel Maxim using IMS Development Environment (version 1.80 build 5127.24028)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.

package ims.emergency.forms.dischargedetails_prescription;

import ims.admin.vo.MenuActionVo;
import ims.configuration.AppRight;
import ims.configuration.gen.ConfigFlag;
import ims.core.admin.vo.CareContextRefVo;
import ims.core.vo.AuthoringInformationVo;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.PatientMedicationLiteVo;
import ims.core.vo.PatientMedicationLiteVoCollection;
import ims.domain.exceptions.StaleObjectException;
import ims.emergency.vo.AppFormForPrescriptionVo;
import ims.emergency.vo.EDPrescriptionVo;
import ims.emergency.vo.EDPrescriptionVoCollection;
import ims.emergency.vo.enums.EdAssessment_CustomControlsEvents;
import ims.framework.FormName;
import ims.framework.controls.DynamicGridCell;
import ims.framework.controls.DynamicGridColumn;
import ims.framework.controls.DynamicGridRow;
import ims.framework.controls.DynamicGridRowCollection;
import ims.framework.enumerations.Alignment;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.DynamicCellType;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.interfaces.IAppRole;
import ims.framework.utils.Color;
import ims.framework.utils.DateTime;
import ims.framework.utils.DateTimeFormat;

import java.util.ArrayList;

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

	private static final int COL_AUTH_DATE = 0;
	private static final int COL_AUTH_USER = 1;
	private static final int COL_MEDS = 2;
	private static final int COL_FREQUENCY = 3;
	private static final int COL_DAYS_SUPPLY = 4;
	private static final int COL_PRESC_COMPLETED = 5;
	private static final int COL_PRESC_PRINTED = 6;
	private static final int COL_DUMMY = 7;

	private static final String PrescriptionRecord = "-6";
	private static final String NewPrescriptionRecord = "-7";
	private static final String PrescriptionMeds = "-8";

	private static final String COL_MED_FREQUENCY_CAPTION = "Frequency";
	private static final String COL_MED_NO_OF_DAYS_SUPPLY_CAPTION = "No. of Days Supply";
	private static final String COL_MED_NAME_CAPTION = "Medication";
	
	private static final int PRINT_PRESCRIPTION_ACTION = 5630008;
	private static final int REPRINT_PRESCRIPTION_ACTION = 5630009;


	//---------------- Component interface methods

	public void initialize(Boolean isReadOnlyMode,CareContextRefVo careContextRef)

	{
		form.getLocalContext().setCareContext(domain.getCareContextShort(careContextRef));
		form.getLocalContext().setSelectedPrescription(null);
		form.getLocalContext().setReadOnly(isReadOnlyMode);
		initializeScreen();
		open(true);

	}

	
	public void setReadOnly(Boolean isReadOnly)
	{
		form.getLocalContext().setReadOnly(isReadOnly);
		updateControlsState();
	}
	
	public EdAssessment_CustomControlsEvents getSelectedEvent()
	{
		return form.getLocalContext().getSelectedEvent();
	}
	
	public void resetSelectedEvent()
	{
		form.getLocalContext().setSelectedEvent(null);
		
	}

	//---------------------------------------------------

	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.getLocalContext().setSelectedEvent(EdAssessment_CustomControlsEvents.CANCEL);
		form.fireCustomControlValueChanged();
		open(false);
	}


	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.getLocalContext().setSelectedEvent(EdAssessment_CustomControlsEvents.SAVE);
		form.fireCustomControlValueChanged();
		
		boolean isRecordEdited = form.dynGridPrescriptions().getValue() instanceof EDPrescriptionVo ? ((EDPrescriptionVo)form.dynGridPrescriptions().getValue()).getID_EDPrescription() != null : form.dynGridPrescriptions().getValue() instanceof PatientMedicationLiteVo ?  ((EDPrescriptionVo)form.dynGridPrescriptions().getSelectedRow().getParent().getValue()).getID_EDPrescription() != null : false;
		if (save(isRecordEdited, false))
			open(false);
	}

	protected void onFormOpen(Object[] args) throws PresentationLogicException
	{
	
		
	}

	protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
	{
		switch (menuItemID)
		{
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.NEW_PRES:
			addNewPrescriptionRecord();
			addNewMedication();
			break;
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.EDIT_PRES:
			editPrescription();
			break;	
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.NEW_MEDICATION:
			addNewMedication();
			break;
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.EDIT_MED:
			editMedication();
			break;
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.REMOVE_MED:
			removeMedication();
			break;
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.RIE_MED:
			markMedicationAsRIE((PatientMedicationLiteVo)form.dynGridPrescriptions().getSelectedRow().getValue());
			break;
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.RIE_PRESC:
			markPrescriptionAsRie((EDPrescriptionVo)form.dynGridPrescriptions().getSelectedRow().getValue());
			break;	
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.PRINT:
			form.getLocalContext().setbReprintActionSelected(false);
			printPrescription((EDPrescriptionVo)form.dynGridPrescriptions().getSelectedRow().getValue());
			break;
		case GenForm.ContextMenus.EmergencyNamespace.PrescriptionMenu.REPRINT:
			form.getLocalContext().setbReprintActionSelected(true);
			rePrintPrescription((EDPrescriptionVo)form.dynGridPrescriptions().getSelectedRow().getValue());
			break;	
		}	
		updateControlsState();
	}


	private void rePrintPrescription(EDPrescriptionVo value)
	{
		if(!(form.dynGridPrescriptions().getValue() instanceof EDPrescriptionVo))
			return;
		
		form.getGlobalContext().Emergency.setEDPrescriptionRef((EDPrescriptionVo)form.dynGridPrescriptions().getSelectedRow().getValue());
		engine.open(form.getForms().Clinical.PrescriptionPrintReprintDialog, new Object[] {form.getLocalContext().getbReprintActionSelected(), getDeniedActionForCurrentUser(engine.getLoggedInRole(), engine.getFormName().getID())});
		
	}

	private void printPrescription(EDPrescriptionVo value)
	{
		if(!(form.dynGridPrescriptions().getValue() instanceof EDPrescriptionVo))
			return;
		
		form.getGlobalContext().Emergency.setEDPrescriptionRef((EDPrescriptionVo)form.dynGridPrescriptions().getSelectedRow().getValue());
		engine.open(form.getForms().Clinical.PrescriptionPrintReprintDialog, new Object[] {form.getLocalContext().getbReprintActionSelected(), getDeniedActionForCurrentUser(engine.getLoggedInRole(), engine.getFormName().getID())});
		
	}
	
	private ArrayList<Integer> getDeniedActionForCurrentUser(IAppRole role, Integer formID) 
	{		
		if(role == null || formID == null)
			return null;
		
		ArrayList<Integer> deniedActionsList = new ArrayList<Integer>();
		AppFormForPrescriptionVo currentForm = domain.getAppFormWithMenuActions(formID);
				
		for(MenuActionVo menuAction : currentForm.getMenuActions())
		{
			if(menuAction == null)
				continue;
			
			if(!role.hasMenuActionRight(currentForm, menuAction) && (menuAction.getID_MenuAction().equals(PRINT_PRESCRIPTION_ACTION) || menuAction.getID_MenuAction().equals(REPRINT_PRESCRIPTION_ACTION)));
			{
				deniedActionsList.add(menuAction.getID_MenuAction());
			}
		}
		
		return deniedActionsList;
	}	
		
	protected void onDynGridPrescriptionsRowSelectionChanged(DynamicGridRow row) throws PresentationLogicException
	{
		
		if (FormMode.VIEW.equals(form.getMode()))
			form.getLocalContext().setSelectedPrescription(row.getIdentifier().equals(PrescriptionRecord)  ? (EDPrescriptionVo)row.getValue() : (row.getIdentifier().equals(PrescriptionMeds) && row.getParent().getIdentifier().equals(PrescriptionRecord)) ? (EDPrescriptionVo) row.getParent().getValue() : null);
		form.getGlobalContext().Emergency.setEDPrescriptionRef(form.getLocalContext().getSelectedPrescription());
		updateControlsState();

	}
	protected void onFormModeChanged() 
	{
		form.getLocalContext().setSelectedEvent(EdAssessment_CustomControlsEvents.FORMMODECHANGED);
		form.fireCustomControlValueChanged();
		
		if (form.getMode().equals(FormMode.VIEW))
		{
			form.getLocalContext().setPrescriptionRecordAdded(false);
		}
		
		updateDynGridControls(form.dynGridPrescriptions(), FormMode.EDIT.equals(form.getMode()));
		
		updateControlsState();
	}
	
	private void updateDynGridControls (ims.framework.controls.DynamicGrid grid, boolean isUnavailable)
	{
		DynamicGridRowCollection rowsColl = grid.getRows();
		DynamicGridRow selectedRow = grid.getSelectedRow();
		
		boolean isHCPUser = domain.getHcpLiteUser() != null;
				
		if (rowsColl == null || rowsColl.size() == 0)
			return;
		for (int i=0; i <rowsColl.size();i++)
		{
			if (rowsColl.get(i) == null)
				continue;
			
			if (rowsColl.get(i).getValue() instanceof EDPrescriptionVo && DynamicCellType.BUTTON.equals(rowsColl.get(i).getCells().get(getColumn(COL_PRESC_COMPLETED)).getType()))
				rowsColl.get(i).getCells().get(getColumn(COL_PRESC_COMPLETED)).setReadOnly(isUnavailable || Boolean.TRUE.equals(form.getLocalContext().getReadOnly()) || !isHCPUser);
			//if (selectedRow != null && ((!selectedRow.equals(rowsColl.get(i)) && rowsColl.get(i).getIdentifier().equals(PrescriptionRecord)) || (selectedRow.equals(rowsColl.get(i)) && rowsColl.get(i).getIdentifier().equals(NewPrescriptionRecord))) && DynamicCellType.DATETIME.equals(rowsColl.get(i).getCells().get(getColumn(COL_AUTH_DATE)).getType()))
			if (selectedRow != null && !selectedRow.equals(rowsColl.get(i)) && rowsColl.get(i).getValue() instanceof EDPrescriptionVo && DynamicCellType.DATETIME.equals(rowsColl.get(i).getCells().get(getColumn(COL_AUTH_DATE)).getType()))
				rowsColl.get(i).getCells().get(getColumn(COL_AUTH_DATE)).setReadOnly(true);
		
			if (selectedRow == null || selectedRow.equals(rowsColl.get(i)) || (selectedRow.getParent() != null && selectedRow.getParent().equals(rowsColl.get(i))) ||(rowsColl.get(i).getParent() != null && selectedRow.getParent() != null && selectedRow.getParent().equals(rowsColl.get(i).getParent())))
			    continue;
			
			if (rowsColl.get(i).getRows() != null)	
			{
					for (int j=0; j< rowsColl.get(i).getRows().size(); j++)
					{
						if (rowsColl.get(i).getRows().get(j) == null)
							continue;
						rowsColl.get(i).getRows().get(j).setSelectable(!isUnavailable);
					}
			
			}
			rowsColl.get(i).setSelectable(!isUnavailable);			
		}

	}
	protected void onDynGridPrescriptionsCellButtonClicked(DynamicGridCell cell)
	{
		if (!DynamicCellType.BUTTON.equals(cell.getType()) || cell.getRow().getIdentifier().equals(NewPrescriptionRecord))
			return;
		
		doCompletion(cell);
		
	}


	private void doCompletion(DynamicGridCell cell)
	{
		form.dynGridPrescriptions().setValue(cell.getRow().getValue());
		
		form.getLocalContext().setSelectedEvent(EdAssessment_CustomControlsEvents.SAVE);
		form.fireCustomControlValueChanged();		
		
		if (save(true,true))
		{	
			cell.clear();
			open(false);
		}
	}

	protected void onDynGridPrescriptionsCellValueChanged(DynamicGridCell cell)
	{
		if (DynamicCellType.DATETIME.equals(cell.getType()) && cell.getValue() == null)
		{
			
		}
		
	}
	
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if (formName.equals(form.getForms().Core.RieConfirmationDialog) && DialogResult.OK.equals(result))
		{
			doRIE();
		}

		if (DialogResult.OK.equals(result) && formName.equals(form.getForms().Clinical.PrescriptionDialog))
		{
			addMedication(form.getGlobalContext().Emergency.getPrescriptionDrug(), null, false, form.getGlobalContext().Emergency.getPrescriptionDrug().getID_PatientMedication() == null);
			form.setMode(FormMode.EDIT);

		}
		if (formName.equals(form.getForms().Clinical.PrescriptionPrintReprintDialog))
		{
			open(false);
		}
		
	}
	private void markPrescriptionAsRie(EDPrescriptionVo value)
	{
		if (value == null)
			return;

		form.getLocalContext().setPrescriptionToBeRIEd(domain.getPrescription(value));
		engine.open(form.getForms().Core.RieConfirmationDialog);

	}

	private void markMedicationAsRIE(PatientMedicationLiteVo value)
	{
		if (value == null)
			return;

		form.getLocalContext().setMedicationToBeRIEd(value);
		form.getLocalContext().setPrescriptionToBeRIEd(null);
		engine.open(form.getForms().Core.RieConfirmationDialog);
	}

	private String[] validateUI()
	{
		ArrayList<String> errors = new ArrayList<String>();

		if (checkForPrescriptionWithoutMeds())
		{
			errors.add("Cannot save a prescription record without medications prescribed.");

		}
		if (form.dynGridPrescriptions().getRows() == null || form.dynGridPrescriptions().getRows().size() ==0)
		{	
			errors.add("At least one valid prescription is required to save correctly");
		}
		
		return errors.toArray(new String[errors.size()]);
	}
	private boolean save(boolean isRecordEditMode, boolean markComplete)
	{
		EDPrescriptionVo prescriptionsVo = populateDataFromScreen(isRecordEditMode,markComplete);

		String[] str = markComplete ? prescriptionsVo.validate() : prescriptionsVo.validate(validateUI());

		if (str != null && str.length > 0)
		{
			engine.showErrors("Invalid Prescription", str);
			return false;
		}

		try
		{		
			form.getLocalContext().setSelectedPrescription(domain.savePrescription(prescriptionsVo));
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			open(false);
			return false;
		}

		return true;
	}

	private AuthoringInformationVo populateAuthoringInfoData(DynamicGridCell cell, boolean isAuthoringInfo)
	{
		AuthoringInformationVo authoringInfo = new AuthoringInformationVo();

		authoringInfo.setAuthoringHcp((HcpLiteVo) domain.getHcpLiteUser());
		authoringInfo.setAuthoringDateTime(isAuthoringInfo ? (cell != null && cell.getValue() != null ? (DateTime) cell.getValue() : new DateTime()) : new DateTime());

		return authoringInfo;	
	}

	private EDPrescriptionVo populateDataFromScreen(boolean isRecordEditMode, boolean markComplete)
	{
		EDPrescriptionVo prescription = null;
		if ( form.dynGridPrescriptions().getSelectedRow() != null && form.dynGridPrescriptions().getSelectedRow().getValue() instanceof EDPrescriptionVo)
		{	
			prescription = (EDPrescriptionVo) form.dynGridPrescriptions().getSelectedRow().getValue();
		} 
		
		if ( form.dynGridPrescriptions().getSelectedRow() != null && form.dynGridPrescriptions().getSelectedRow().getValue() instanceof PatientMedicationLiteVo)
		{	
			prescription = (EDPrescriptionVo) form.dynGridPrescriptions().getSelectedRow().getParent().getValue();
		} 

		DynamicGridRow selectedPrescRow = null;
		AuthoringInformationVo auth  = new AuthoringInformationVo();
		PatientMedicationLiteVoCollection medicationColl = new PatientMedicationLiteVoCollection();
		
		if (form.dynGridPrescriptions().getSelectedRow().getValue() instanceof EDPrescriptionVo)
			selectedPrescRow = form.dynGridPrescriptions().getSelectedRow();
		else if (form.dynGridPrescriptions().getSelectedRow().getValue() instanceof PatientMedicationLiteVo)
			selectedPrescRow = form.dynGridPrescriptions().getSelectedRow().getParent();
		
		if (selectedPrescRow != null && selectedPrescRow.getValue() instanceof EDPrescriptionVo)
		{	
			int medications = selectedPrescRow.getRows().size();
			for (int j = 0; j < medications; j++)
			{
				if (selectedPrescRow.getRows().get(j).getValue() != null && selectedPrescRow.getRows().get(j).getValue() instanceof PatientMedicationLiteVo)
				{
					PatientMedicationLiteVo medication = (PatientMedicationLiteVo) selectedPrescRow.getRows().get(j).getValue();

					medicationColl.add(medication);
				}
			}
			auth = populateAuthoringInfoData(selectedPrescRow.getCells().get(getColumn(COL_AUTH_DATE)),true);
		}
		
		prescription.setMedications(medicationColl);
		prescription.setPatient(form.getGlobalContext().Core.getPatientShort());
		prescription.setEpisode(form.getGlobalContext().Core.getEpisodeofCareShort());
		prescription.setAttendance(form.getLocalContext().getCareContext());
		
		AuthoringInformationVo recInfo = populateAuthoringInfoData(null,false);
		if (!isRecordEditMode)
		{	
			prescription.setRecordingInformation(recInfo);
		}
		if (markComplete)
		{	
			prescription.setIsCompleted(markComplete);
			prescription.setCompletingInformation(recInfo);
		}
				
		prescription.setAuthoringInformation(auth);

		return prescription;			
	}

	private void doRIE() //WDEV-19588
	{
		if (form.getLocalContext().getPrescriptionToBeRIEdIsNotNull())
		{
			if (domain.isStale(form.getLocalContext().getPrescriptionToBeRIEd())) //WDEV-19588
			{
				engine.showErrors(new String[]{ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()});
				open(false);
				return;
			}
			try
			{
				if (form.getLocalContext().getPrescriptionToBeRIEd().getMedications() != null)
				{
					for (PatientMedicationLiteVo medication : form.getLocalContext().getPrescriptionToBeRIEd().getMedications())
					{
						if (domain.isStale(medication))
						{
							engine.showErrors(new String[]{ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()});
							open(false);
							return;
						}
						try
						{
						domain.markAsRie(medication, engine.getFormName(), 
								form.getGlobalContext().Core.getPatientShort().getID_Patient(), 
								null,
								form.getGlobalContext().Core.getCurrentCareContextIsNotNull()? form.getGlobalContext().Core.getCurrentCareContext().getID_CareContext():null,
										form.getGlobalContext().Core.getRieMessage());
						}
						catch (StaleObjectException e)
						{
							engine.showErrors(new String[]{ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()});
							open(false);
							return;
						}
						
					}
				}
				domain.markAsRie(form.getLocalContext().getPrescriptionToBeRIEd(), engine.getFormName(), 
						form.getGlobalContext().Core.getPatientShort().getID_Patient(), 
						null,
						form.getGlobalContext().Core.getCurrentCareContextIsNotNull()? form.getGlobalContext().Core.getCurrentCareContext().getID_CareContext():null,
								form.getGlobalContext().Core.getRieMessage());
			}
			catch (StaleObjectException e)
			{
				engine.showErrors(new String[]{ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()});
				open(false);
				return;
			}
			
			form.getLocalContext().setPrescriptionToBeRIEd(null);
			form.getLocalContext().setMedicationToBeRIEd(null);
			form.getLocalContext().setSelectedPrescription(null);
		}
		else if (form.getLocalContext().getMedicationToBeRIEdIsNotNull())
		{
			if (domain.isStale(form.getLocalContext().getMedicationToBeRIEd())) //WDEV-19588
			{
				engine.showErrors(new String[]{ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()});
				open(false);
				return;
			}
			try
			{
				domain.markAsRie(form.getLocalContext().getMedicationToBeRIEd(), engine.getFormName(), 
						form.getGlobalContext().Core.getPatientShort().getID_Patient(), 
						null,
						form.getGlobalContext().Core.getCurrentCareContextIsNotNull()? form.getGlobalContext().Core.getCurrentCareContext().getID_CareContext():null,
								form.getGlobalContext().Core.getRieMessage());
			}
			catch (StaleObjectException e)
			{
				engine.showErrors(new String[]{ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()});
				open(false);
				return;
			}
						
			form.getLocalContext().setMedicationToBeRIEd(null);
		}
		
		open(false);		
	}
	private boolean checkForPrescriptionWithoutMeds()
	{
		int prescriptions = form.dynGridPrescriptions().getRows().size();

		for (int i = 0; i < prescriptions; i++)
		{
			if (form.dynGridPrescriptions().getRows().get(i).getValue() != null && form.dynGridPrescriptions().getRows().get(i).getValue() instanceof EDPrescriptionVo &&  form.dynGridPrescriptions().getRows().get(i).getIdentifier().equals(NewPrescriptionRecord))
			{
				EDPrescriptionVo prescription = (EDPrescriptionVo) form.dynGridPrescriptions().getRows().get(i).getValue();

				if (prescription != null && form.dynGridPrescriptions().getRows().get(i).getRows().size() == 0)
					return true;
			}
		}

		return false;
	}
	
	
	private void open(boolean bCalledFromInit)
	{
		listPrescriptions(form.getLocalContext().getCareContext());
		if (bCalledFromInit && form.dynGridPrescriptions().getRows() != null && form.dynGridPrescriptions().getRows().size() > 0) //WDEV-18973
		{
			form.dynGridPrescriptions().setSelectedRow(form.dynGridPrescriptions().getRows().get(0));
		}
		if (!bCalledFromInit && form.getLocalContext().getSelectedPrescription() != null)
			form.dynGridPrescriptions().setValue(domain.getPrescription((EDPrescriptionVo)form.getLocalContext().getSelectedPrescription()));
		
		form.setMode(FormMode.VIEW);

	}
	private void listPrescriptions(CareContextRefVo careContext)
	{
		EDPrescriptionVoCollection coll = domain.listPrescriptions(careContext);
		populateScreenFromData(coll);

	}

	private void populateScreenFromData(EDPrescriptionVoCollection coll)
	{
		form.dynGridPrescriptions().getRows().clear();
				
		if (coll == null || coll.size() == 0)
			return;
		for (int i=0;i<coll.size();i++)
		{
			if (coll.get(i) == null)
				continue;
			addPrescriptionRecord(null, coll.get(i), false,true);
		}		
	}

	private void removeMedication()
	{
		if (form.dynGridPrescriptions().getValue() instanceof PatientMedicationLiteVo && form.getMode().equals(FormMode.EDIT))
		{			
			DynamicGridRow row = form.dynGridPrescriptions().getSelectedRow();
			form.dynGridPrescriptions().getRows().remove(row);
			form.dynGridPrescriptions().setSelectedRow(row.getParent());
		}
		
	}

	private void addMedication(PatientMedicationLiteVo patientMedication, DynamicGridRow row, boolean readOnly, boolean newRecord)// WDEV-13584
	{
		if (row == null)
		{
			row = form.dynGridPrescriptions().getSelectedRow();
		}
		if (row.getIdentifier() != null)  
		{		

			if (row.getIdentifier().equals(NewPrescriptionRecord) || row.getIdentifier().equals(PrescriptionRecord))
			{
				addMedicationRow(patientMedication,row.getRows().newRow(), readOnly, newRecord);// WDEV-13584
			}
			else if (row.getIdentifier().equals(PrescriptionMeds))
			{
				addMedicationRow(patientMedication, newRecord ? row.getParent().getRows().newRow() : row,readOnly, newRecord);// WDEV-13584
			}
		}

		row.setExpanded(true);
	}
	private void addMedicationRow(PatientMedicationLiteVo patientMedicationLiteVo,DynamicGridRow medRow, boolean readOnly, boolean newRecord)
	{
		if (medRow == null)
			return;
				
		medRow.setIdentifier(PrescriptionMeds);
		medRow.setReadOnly(readOnly);

		DynamicGridColumn coll = form.dynGridPrescriptions().getColumns().getByIdentifier(COL_AUTH_USER);
		DynamicGridCell userCell = medRow.getCells().newCell(coll, DynamicCellType.HTMLVIEW);
		String cellDisplayText = medRow.getParent().getValue() instanceof EDPrescriptionVo ? ((EDPrescriptionVo) medRow.getParent().getValue()).getRecordingInformationIsNotNull() && ((EDPrescriptionVo) medRow.getParent().getValue()).getRecordingInformation().getAuthoringHcp() != null ? ((EDPrescriptionVo) medRow.getParent().getValue()).getRecordingInformation().getAuthoringHcp().getIMosName() : "" : "";
		userCell.setValue(cellDisplayText);
		userCell.setTooltip(cellDisplayText);
		userCell.setReadOnly(true);

		coll = form.dynGridPrescriptions().getColumns().getByIdentifier(COL_MEDS);
		DynamicGridCell medCell = medRow.getCells().newCell(coll, DynamicCellType.HTMLVIEW);
		coll.setCaption(COL_MED_NAME_CAPTION);
		medCell.setValue(patientMedicationLiteVo.getOtherMedicationText());
		medCell.setTooltip(patientMedicationLiteVo.getOtherMedicationText());
		medCell.setReadOnly(true);

		coll = form.dynGridPrescriptions().getColumns().getByIdentifier(COL_FREQUENCY);
		DynamicGridCell freqCell = medRow.getCells().newCell(coll, DynamicCellType.HTMLVIEW);
		coll.setCaption(COL_MED_FREQUENCY_CAPTION);
		freqCell.setReadOnly(true);

		freqCell.setValue(patientMedicationLiteVo != null ? (patientMedicationLiteVo.getFrequencyIsNotNull() ? patientMedicationLiteVo.getFrequency().getIItemText() : null) : null);
		freqCell.setTooltip(patientMedicationLiteVo != null ? (patientMedicationLiteVo.getFrequencyIsNotNull() ? patientMedicationLiteVo.getFrequency().getIItemText() : "") : "");
		
		coll = form.dynGridPrescriptions().getColumns().getByIdentifier(COL_DAYS_SUPPLY);
		coll.setCaption(COL_MED_NO_OF_DAYS_SUPPLY_CAPTION);
		
		DynamicGridCell amountCell = medRow.getCells().newCell(coll, DynamicCellType.HTMLVIEW);
		amountCell.setReadOnly(true);
		amountCell.setValue(patientMedicationLiteVo != null && patientMedicationLiteVo.getNoDaysSupplyIsNotNull() ?  "<p style=\"text-align: center;\">" +  String.valueOf(patientMedicationLiteVo.getNoDaysSupply().intValue()) + "</p>" : null);
		amountCell.setTooltip(patientMedicationLiteVo != null && patientMedicationLiteVo.getNoDaysSupplyIsNotNull() ? String.valueOf(patientMedicationLiteVo.getNoDaysSupply().intValue()) : "");
		
		medRow.setValue(patientMedicationLiteVo);

		if(newRecord)
			medRow.setBackColor(Color.Beige);		

	}

	private void updateControlsState()
	{
		boolean isHCPUser = domain.getHcpLiteUser() != null;
		boolean canPrescribe = engine.hasRight(AppRight.ED_CAN_PRESCRIBE);
		
		Object selectedGridRecord = form.dynGridPrescriptions().getValue();
		DynamicGridRow selectedGridRowParent = form.dynGridPrescriptions().getSelectedRow() != null ? form.dynGridPrescriptions().getSelectedRow().getParent() : null;
		
		boolean isSavedPrescription =  selectedGridRecord instanceof EDPrescriptionVo &&  ((EDPrescriptionVo) selectedGridRecord).getID_EDPrescriptionIsNotNull();
		boolean isSavedMedication =  selectedGridRecord instanceof PatientMedicationLiteVo &&  ((PatientMedicationLiteVo) selectedGridRecord).getID_PatientMedicationIsNotNull();
		boolean isUnsavedMedication =  selectedGridRecord instanceof PatientMedicationLiteVo &&  ((PatientMedicationLiteVo) selectedGridRecord).getID_PatientMedication() == null;
		boolean isCompletePrescription = isSavedPrescription && Boolean.TRUE.equals(((EDPrescriptionVo) selectedGridRecord).getIsCompleted());
		boolean isPrintedPrescription = isCompletePrescription && Boolean.TRUE.equals(((EDPrescriptionVo) selectedGridRecord).getIsPrinted());
		boolean isParentPrescriptionComplete = selectedGridRecord instanceof PatientMedicationLiteVo && selectedGridRowParent != null && Boolean.TRUE.equals(((EDPrescriptionVo) selectedGridRowParent.getValue()).getIsCompleted());
		boolean isParentPrescriptionPrinted = selectedGridRecord instanceof PatientMedicationLiteVo && selectedGridRowParent != null && Boolean.TRUE.equals(((EDPrescriptionVo) selectedGridRowParent.getValue()).getIsPrinted());
					
		if (!isHCPUser || Boolean.TRUE.equals(form.getLocalContext().getReadOnly()))
		{
			form.getContextMenus().Emergency.hideAllPrescriptionMenuMenuItems();
			return;
		}
		form.getContextMenus().Emergency.getPrescriptionMenuNEW_PRESItem().setVisible(FormMode.VIEW.equals(form.getMode()) && isHCPUser && (selectedGridRecord == null || selectedGridRecord instanceof EDPrescriptionVo));
		form.getContextMenus().Emergency.getPrescriptionMenuEDIT_PRESItem().setVisible(FormMode.VIEW.equals(form.getMode()) && isHCPUser &&  selectedGridRecord instanceof EDPrescriptionVo && !isCompletePrescription);
		form.getContextMenus().Emergency.getPrescriptionMenuNEW_MEDICATIONItem().setVisible(isHCPUser && (selectedGridRecord instanceof EDPrescriptionVo && !isCompletePrescription) || (FormMode.VIEW.equals(form.getMode()) && selectedGridRecord instanceof PatientMedicationLiteVo && selectedGridRowParent.getIdentifier().equals(PrescriptionRecord) && !isParentPrescriptionComplete));
		form.getContextMenus().Emergency.getPrescriptionMenuEDIT_MEDItem().setVisible(isHCPUser && isSavedMedication && !isParentPrescriptionComplete);
		form.getContextMenus().Emergency.getPrescriptionMenuREMOVE_MEDItem().setVisible(FormMode.EDIT.equals(form.getMode())&& isHCPUser && isUnsavedMedication);
		form.getContextMenus().Emergency.getPrescriptionMenuRIE_MEDItem().setVisible(FormMode.VIEW.equals(form.getMode())&& isHCPUser && isSavedMedication && !isParentPrescriptionPrinted);
		form.getContextMenus().Emergency.getPrescriptionMenuRIE_PRESCItem().setVisible(FormMode.VIEW.equals(form.getMode())&& isHCPUser && isSavedPrescription);
		form.getContextMenus().Emergency.getPrescriptionMenuPRINTItem().setVisible(FormMode.VIEW.equals(form.getMode()) && isHCPUser && canPrescribe && isCompletePrescription && !isPrintedPrescription);
		form.getContextMenus().Emergency.getPrescriptionMenuREPRINTItem().setVisible(FormMode.VIEW.equals(form.getMode()) && isHCPUser && canPrescribe && isPrintedPrescription);
	}

	private void editPrescription() 
	{
		if(!(form.dynGridPrescriptions().getValue() instanceof EDPrescriptionVo))
			return;
		form.dynGridPrescriptions().getSelectedRow().getCells().get(getColumn(COL_AUTH_DATE)).setReadOnly(false);
		form.setMode(FormMode.EDIT);

	}
	private void editMedication()
	{
		if(!(form.dynGridPrescriptions().getValue() instanceof PatientMedicationLiteVo))
			return;
		form.dynGridPrescriptions().getSelectedRow().getParent().getCells().get(getColumn(COL_AUTH_DATE)).setReadOnly(false);
		engine.open(form.getForms().Clinical.PrescriptionDialog, new Object[]{(PatientMedicationLiteVo) form.dynGridPrescriptions().getValue()});


	}
	private void addNewMedication()
	{
		form.getGlobalContext().Emergency.setMedsAlreadyAddedInPrescription(getDrugsFromPrescription());
		engine.open(form.getForms().Clinical.PrescriptionDialog, new Object[] {null});

	}

	private void addNewPrescriptionRecord()
	{
		if (form.getLocalContext().getPrescriptionRecordAddedIsNotNull() && !form.getLocalContext().getPrescriptionRecordAdded())
		{
			form.getLocalContext().setPrescriptionRecordAdded(true);
			form.getLocalContext().setSelectedPrescription(null);
			DynamicGridRow row = null;
			if (form.dynGridPrescriptions().getRows().size() == 0)
			{
				row = form.dynGridPrescriptions().getRows().newRow(true);
			}
			else
			{
				row = form.dynGridPrescriptions().getRows().newRowBefore(form.dynGridPrescriptions().getRows().get(0), true);
			}

			addPrescriptionRecord(row, null, true,false);
			form.setMode(FormMode.EDIT);
		}
	}	
	private void addPrescriptionRecord(DynamicGridRow row, EDPrescriptionVo prescriptionVo, boolean newRecord, boolean readOnly)
	{
		AuthoringInformationVo authoringInfo = new AuthoringInformationVo();
		HcpLiteVo currentHCPUser = (HcpLiteVo) domain.getHcpLiteUser();
		if (prescriptionVo == null)
		{
			prescriptionVo = new EDPrescriptionVo();
		}

		if (row == null)
			row = newRecord ? form.dynGridPrescriptions().getRows().newRow(true) : form.dynGridPrescriptions().getRows().newRow(); //WDEV-18973

		if (newRecord)
			row.setIdentifier(NewPrescriptionRecord);
		else
			row.setIdentifier(PrescriptionRecord);
		
		DynamicGridCell prescDateCell = row.getCells().newCell(getColumn(COL_AUTH_DATE), DynamicCellType.DATETIME);
		prescDateCell.setValue(prescriptionVo != null ? (prescriptionVo.getAuthoringInformationIsNotNull() ? prescriptionVo.getAuthoringInformation().getAuthoringDateTime():new DateTime()) : new DateTime());
		prescDateCell.setReadOnly(readOnly);
		prescDateCell.setAutoPostBack(true);
		
		DynamicGridCell prescUserCell = row.getCells().newCell(getColumn(COL_AUTH_USER), DynamicCellType.HTMLVIEW);
		prescUserCell.setReadOnly(Boolean.TRUE);
		prescUserCell.setValue(prescriptionVo != null ? (prescriptionVo.getRecordingInformationIsNotNull() && prescriptionVo.getRecordingInformation().getAuthoringHcpIsNotNull() ? prescriptionVo.getRecordingInformation().getAuthoringHcp().getIMosName() : currentHCPUser != null ? currentHCPUser.getIMosName() : null) : currentHCPUser != null ? currentHCPUser.getIMosName() : null);
		prescUserCell.setTooltip(prescriptionVo != null ? (prescriptionVo.getRecordingInformationIsNotNull() && prescriptionVo.getRecordingInformation().getAuthoringHcpIsNotNull() ? prescriptionVo.getRecordingInformation().getAuthoringHcp().getIMosName() : currentHCPUser != null ? currentHCPUser.getIMosName() : "") : currentHCPUser != null ? currentHCPUser.getIMosName() : "");

		DynamicCellType cellType = getCellType(newRecord, Boolean.TRUE.equals(prescriptionVo.getIsCompleted()));
		DynamicGridCell completedCell = row.getCells().newCell(getColumn(COL_PRESC_COMPLETED), cellType);
		

		if (DynamicCellType.IMAGE.equals(completedCell.getType()))
		{		
			completedCell.setValue(Boolean.TRUE.equals(prescriptionVo.getIsCompleted()) ? form.getImages().Correspondence.DocumentCompleted16 : null);
			completedCell.setReadOnly(true);
			completedCell.setWidth(completedCell.getColumn().getWidth());
			completedCell.setTooltip(buildCompletingInfoTooltip(prescriptionVo));			
		}
		if (DynamicCellType.BUTTON.equals(completedCell.getType()))
		{		
			completedCell.setButtonText(" Complete ");
			completedCell.setReadOnly(true);
			completedCell.setAutoPostBack(true);
		}
		
		if (row.getIdentifier().equals(PrescriptionRecord) && Boolean.TRUE.equals(prescriptionVo.getIsPrinted()))
		{		
			DynamicGridCell printedCell = row.getCells().newCell(getColumn(COL_PRESC_PRINTED), DynamicCellType.IMAGE);
			printedCell.setValue(form.getImages().Correspondence.Printer);
			printedCell.setTooltip("Printed");
		}
		
		authoringInfo = populateAuthoringInfoData(prescDateCell, true);
				
		prescriptionVo.setAuthoringInformation(authoringInfo);
		row.setValue(prescriptionVo);
				
		if (prescriptionVo.getMedications() == null || prescriptionVo.getMedications().size() == 0)
			return;
		for (int i = 0; i < prescriptionVo.getMedications().size(); i++)
		{
			PatientMedicationLiteVo patientMedication = prescriptionVo.getMedications().get(i);
			if (patientMedication == null)
				continue;
			addMedication(patientMedication, row, true, newRecord);

		}
	}
	
	private DynamicCellType getCellType(boolean newRecord, boolean isComplete)
	{
		if (newRecord)
			return DynamicCellType.EMPTY;
		 return isComplete ?  DynamicCellType.IMAGE /*DynamicCellType.BOOL */ : DynamicCellType.BUTTON;
	}
	private String buildCompletingInfoTooltip(EDPrescriptionVo prescriptionVo)
	{
		if (prescriptionVo == null || prescriptionVo.getCompletingInformation() == null)
			return null;
		StringBuilder tooltip = new StringBuilder();
		if (prescriptionVo.getCompletingInformation().getAuthoringHcp() != null)
		{
			tooltip.append("Completing HCP: <b>" + prescriptionVo.getCompletingInformation().getAuthoringHcp().getIMosName() + "</b>");
			tooltip.append("<br/>");
		}
		if (prescriptionVo.getCompletingInformation().getAuthoringDateTime() != null)
		{
			tooltip.append("Completed Date/Time: <b>" + prescriptionVo.getCompletingInformation().getAuthoringDateTime().toString(DateTimeFormat.STANDARD) + "</b>");
		}
		return tooltip.toString();
	}

	private ArrayList<Integer> getDrugsFromPrescription()
	{
		DynamicGridRow prescRow = null; 
		if (form.dynGridPrescriptions().getSelectedRow().getIdentifier().equals(PrescriptionRecord) || form.dynGridPrescriptions().getSelectedRow().getIdentifier().equals(NewPrescriptionRecord))
			prescRow = form.dynGridPrescriptions().getSelectedRow();
		if (form.dynGridPrescriptions().getSelectedRow().getIdentifier().equals(PrescriptionMeds))
			prescRow = form.dynGridPrescriptions().getSelectedRow().getParent();

		if (prescRow == null)
			return null;
		
		ArrayList<Integer> existingValues = new ArrayList<Integer>();		
		
		for(int i=0; i<prescRow.getRows().size(); i++)
		{
			if(!(prescRow.getRows().get(i).getValue() instanceof PatientMedicationLiteVo))
				continue;

			PatientMedicationLiteVo drug = (PatientMedicationLiteVo) prescRow.getRows().get(i).getValue();
			if(drug.getMedication() != null)
				existingValues.add(drug.getMedication().getID_Medication());
		}

		if (existingValues == null || existingValues.size() == 0)
			return null;

		return existingValues;
	}

	private DynamicGridColumn getColumn(Integer colFieldName) 
	{
		return form.dynGridPrescriptions().getColumns().getByIdentifier(colFieldName);
	}	

	private void initializeScreen()
	{
		initializePrescriptionsGrid();
		form.setMode(FormMode.VIEW);
	}
	private void initializePrescriptionsGrid() 
	{
		form.dynGridPrescriptions().clear();
		form.dynGridPrescriptions().setSelectable(true);
		
		DynamicGridColumn col = form.dynGridPrescriptions().getColumns().newColumn("Authoring Date/Time", COL_AUTH_DATE);
		col.setWidth(205);
		col.setCanGrow(Boolean.TRUE);
		
		col = form.dynGridPrescriptions().getColumns().newColumn("Authored By", COL_AUTH_USER);
		col.setWidth(130);
		col.setCanGrow(Boolean.TRUE);
		col.setReadOnly(Boolean.TRUE);

		col = form.dynGridPrescriptions().getColumns().newColumn("",COL_MEDS);
		col.setWidth(165);
		col.setCanGrow(Boolean.TRUE);
		col.setReadOnly(Boolean.TRUE);

		col = form.dynGridPrescriptions().getColumns().newColumn("",COL_FREQUENCY);
		col.setWidth(75);
		col.setCanGrow(Boolean.FALSE);
		col.setReadOnly(Boolean.TRUE);

		col = form.dynGridPrescriptions().getColumns().newColumn("",COL_DAYS_SUPPLY);
		col.setWidth(110);
		col.setCanGrow(Boolean.FALSE);
		col.setAlignment(Alignment.CENTER);
		col.setReadOnly(Boolean.TRUE);

		col = form.dynGridPrescriptions().getColumns().newColumn("Complete",COL_PRESC_COMPLETED);
		col.setWidth(100);
		col.setCanGrow(Boolean.TRUE);
		col.setAlignment(Alignment.CENTER);
		col.setHeaderAlignment(Alignment.CENTER);
		col.setReadOnly(Boolean.TRUE);
		
		col = form.dynGridPrescriptions().getColumns().newColumn("",COL_PRESC_PRINTED);
		col.setWidth(30);
		col.setAlignment(Alignment.CENTER);
		col.setCanGrow(Boolean.FALSE);
		
		col = form.dynGridPrescriptions().getColumns().newColumn("",COL_DUMMY);
		col.setWidth(-1);
		col.setVisible(Boolean.FALSE);
		col.setAlignment(Alignment.CENTER);
	}
}
