//#############################################################################
//#                                                                           #
//#  Copyright (C) <2014>  <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/>.    #
//#                                                                           #
//#############################################################################
//#EOH
// This code was generated by Rory Fitzpatrick using IMS Development Environment (version 1.51 build 2477.26137)
// Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved.

package ims.clinical.forms.clinicalnotes;

import ims.configuration.gen.ConfigFlag;
import ims.core.forms.authoringinfo.IComponent;
import ims.core.vo.AuthoringInformationVo;
import ims.core.vo.ClinicalContactShortVo;
import ims.core.vo.ClinicalNoteStatusVo;
import ims.core.vo.ClinicalNoteStatusVoCollection;
import ims.core.vo.ClinicalNotesVo;
import ims.core.vo.ClinicalNotesVoCollection;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.MedicVo;
import ims.core.vo.MemberOfStaffShortVo;
import ims.core.vo.MemberOfStaffVo;
import ims.core.vo.enums.AuthoringLabelType;
import ims.core.vo.lookups.ClinicalNoteType;
import ims.core.vo.lookups.ClinicalNotesStatus;
import ims.core.vo.lookups.ClinicalNotingMode;
import ims.core.vo.lookups.HcpDisType;
import ims.core.vo.lookups.HcpDisTypeCollection;
import ims.core.vo.lookups.SourceOfNote;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.domain.exceptions.UniqueKeyViolationException;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.CodingRuntimeException;
import ims.framework.exceptions.FormOpenException;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.DateTime;

import java.util.ArrayList;

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

	protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException
	{
		//WDEV-2511 
		if (domain.getMosUser() == null)
			throw new FormOpenException("The User Account is not linked to a HCP or Member of Staff, this form will not be active. Please contact the System Administrator.");
		
		form.btnClose().setVisible(engine.isDialog());
		initialiseScreenControls();
		openNotingDetails();
		checkForDiscipline();
		
		if (isDialog() 
			&& form.getGlobalContext().Clinical.getReturnToFormModeIsNotNull()
			&& form.getGlobalContext().Clinical.getReturnToFormMode().equals(FormMode.VIEW))
			form.btnUpdate().setVisible(false);
	}
	
	private void initialiseScreenControls() 
	{
		//WDEV-15382
		form.txtNotes().setVisible(false); 
		form.txtNotes().setEnabled(false);
		form.richNotes().setVisible(true);
		form.richNotes().setEnabled(false);
		
		form.customControlReviewed().ignoreComponentReadonlyFlag(Boolean.TRUE);
		form.chkForReview().setVisible(true);
		form.cmbDiscipline().setVisible(true);
		form.lblDiscipline().setVisible(true);
		form.setcustomControlReviewedVisible(false);
		form.chkMarkAsReviewed().setVisible(false);
		form.customControlAuthoring().setIsRequiredPropertyToControls(true);
		form.cmbDiscipline().clear();
		HcpDisTypeCollection hcpDisTypeColl = (ims.core.vo.lookups.LookupHelper.getHcpDisType(domain.getLookupService()));
		for( int i = 0;i < hcpDisTypeColl.size();i++)
		{
			if(hcpDisTypeColl.get(i).getParent() == null)
				form.cmbDiscipline().newRow(hcpDisTypeColl.get(i), hcpDisTypeColl.get(i).getIItemText(),hcpDisTypeColl.get(i).getImage());
	
		}
	}
	
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.VIEW);
		form.btnClose().setEnabled(true);
		form.richNotes().setEnabled(false); //wdev-15681

		if (isDialog())
			onBtnCloseClick();
		else
			openNotingDetails();
	}
	
	private boolean isDialog()
	{
		return engine.isDialog();
	}
	
	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (save())
		{
			form.richNotes().setEnabled(false);	//wdev-15681
			openNotingDetails();
		}

		form.btnClose().setEnabled(true);
		
	
	}
	
	private String[] getUiErrors() 
	{
		ArrayList<String> errors = new ArrayList<String>();
		
		if(form.cmbStatus().getValue() == null)
		{
			errors.add("Status is mandatory");
		}
		
		if (form.chkForReview().getValue() == true)
		{
			if (form.cmbDiscipline().getValue() == null)
			{
				//form.chkForReview().setValue(false);
				errors.add("If 'For Review' is checked 'Discipline' is mandatory");
			}
		}
		
		if (errors.size() > 0) 
		{
			String[] searchErrors = new String[errors.size()];
			errors.toArray(searchErrors);
			engine.showErrors("Invalid Clinical Notes record", searchErrors);
			return searchErrors;
		}
		return null;
	}
	
	private boolean save() throws PresentationLogicException
	{
//		wdev-8976
		if (form.customControlAuthoring().getValue() != null
			&& (form.customControlAuthoring().getValue().getAuthoringHcp() == null
				|| (form.customControlAuthoring().getValue().getAuthoringHcpIsNotNull()
					&& form.customControlAuthoring().getValue().getAuthoringHcp().getID_Hcp() == null)))
		{
			engine.showMessage("Authoring HCP is mandatory.");
			return false;
		}
			
		ClinicalNotesVo record = populateDataFromScreen(form.getLocalContext().getclinicalNotesVo());
		if (record == null)
			return false;
		
		String[] uiErrors = getUiErrors();
		String[] errors = record.validate(uiErrors);
		if(errors != null && errors.length > 0)
		{
			engine.showErrors(errors);
			
			if (form.chkForReview().getValue() == false)
				form.cmbDiscipline().setEnabled(false);
			else
				form.cmbDiscipline().setEnabled(true);
			
			return false;
		}
		
		try
		{
			record = domain.saveClinicalNotesAndClinicalContact(record,form.getGlobalContext().Core.getCurrentClinicalContact());
		}
		catch(StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			form.getLocalContext().setclinicalNotesVo(record);
			form.getGlobalContext().Clinical.setCurrentClinicalNote(null);
			openNotingDetails();
			return false;
		}
		catch(CodingRuntimeException e)
		{
			if ("ANOTHER_NOTE_FOR_CLINICAL_CONTACT".equals(e.getMessage()))
				throw new FormOpenException("A clinical note of a different type has been created for this clincal contact by another user");
			form.getGlobalContext().Clinical.setCurrentClinicalNote(null);
			engine.showMessage(e.getMessage());
			openNotingDetails();
			return false;
		}
		catch(DomainInterfaceException e)
		{
			engine.showMessage(e.getMessage());
			openNotingDetails();
			return false;
		}
		catch (UniqueKeyViolationException e)
		{
			engine.showMessage(e.getMessage());
			return false;
		}
		
				
		
		form.getLocalContext().setclinicalNotesVo(record);
		form.getGlobalContext().Clinical.setCurrentClinicalNote(record);
		
	
		if (isDialog())
		{		
			onBtnCancelClick();
			onBtnCloseClick();	
		}
		
		return true;
		
	}
	
	private ClinicalNotesVo populateDataFromScreen(ClinicalNotesVo clinicalNotesVo) 
	{
		if (clinicalNotesVo == null)
			clinicalNotesVo = new ClinicalNotesVo();
		
		if ( ! clinicalNotesVo.getCareContextIsNotNull()
			&& clinicalNotesVo.getID_ClinicalNotes() == null)
			clinicalNotesVo.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
		
		if ( ! clinicalNotesVo.getClinicalContactIsNotNull()
			&& clinicalNotesVo.getID_ClinicalNotes() == null)
			clinicalNotesVo.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
		
		MemberOfStaffShortVo mos = null;
		if (getDisciplineForLoggedInUser(clinicalNotesVo) != null)
			mos = getDisciplineForLoggedInUser(clinicalNotesVo);
		else
			return null;
		
		//Save old Status to check for active
		ClinicalNoteStatusVo voPreviousStat = clinicalNotesVo.getCurrentStatus();
		ClinicalNoteStatusVo voStat = new ClinicalNoteStatusVo();
		
		//WDEV-14968
		if (voPreviousStat != null)
		{
			voStat = voPreviousStat;
		}
		
		if(form.getGlobalContext().Core.getClinicalNotingModeIsNotNull()
				&& form.getGlobalContext().Core.getClinicalNotingMode().equals(ClinicalNotingMode.VALIDATE))
		{
			voStat.setClinicalNote(clinicalNotesVo.getClinicalNote());
			voStat.setStatus(ClinicalNotesStatus.ACTIVE);
		}
		else
			voStat.setStatus(form.cmbStatus().getValue());
		
		voStat.setDateTime(new DateTime());
		voStat.setMOS(mos != null ? mos : null);
		
		//In Correct mode, HCP ok and either Active or Correct then be sure status saved is Corrected
		/*if (correctModeIP(voPreviousStat)) 
		{
			voStat.setStatus(ClinicalNotesStatus.CORRECTED);
			clinicalNotesVo.setIsCorrected(new Boolean(true));
		}*/

		
		//If old Status is Active and loggedin user == authoring user......need to save the old Note in the status history
		//In Correct mode
		
		boolean isReviewed = false;
		
		if (form.getGlobalContext().Core.getClinicalNotingModeIsNotNull())
			isReviewed = form.getGlobalContext().Core.getClinicalNotingMode().equals(ClinicalNotingMode.REVIEW);
		
		if (correctModeIP(voPreviousStat) && !isReviewed  &&
				!clinicalNotesVo.getClinicalNote().equals(form.richNotes().getValue())) //In Correct mode) //In Correct mode
		{
			voStat.setClinicalNote(clinicalNotesVo.getClinicalNote());
			clinicalNotesVo.setStatusHistory(addStatusToCollection(clinicalNotesVo.getStatusHistory(), voStat));
			
			voStat.setStatus(ClinicalNotesStatus.CORRECTED);
			clinicalNotesVo.setIsCorrected(new Boolean(true));
		}
		
		if (voStat.getStatusIsNotNull())
			clinicalNotesVo.setCurrentStatus(voStat);
		else
			clinicalNotesVo.setCurrentStatus(voPreviousStat);
		
		if ( ! (clinicalNotesVo.getInHospitalReportIsNotNull() && clinicalNotesVo.getInHospitalReport().equals(Boolean.TRUE))) //WDEV-14968
		{
			clinicalNotesVo.setInHospitalReport(Boolean.FALSE);
		}
		
		if(form.customControlAuthoring().getValue()!=null){
			HcpDisType hcpDisType = 
				form.customControlAuthoring().getValue().getAuthoringHcpIsNotNull()	&& 
					form.customControlAuthoring().getValue().getAuthoringHcp().getHcpTypeIsNotNull() ?
							form.customControlAuthoring().getValue().getAuthoringHcp().getHcpType() : null;
			clinicalNotesVo.setDiscipline(hcpDisType);
		}
		
		if(form.customControlAuthoring().getValue()!=null){
			AuthoringInformationVo voAuthor = new AuthoringInformationVo();
			voAuthor.setAuthoringDateTime(
					form.customControlAuthoring().getValue() != null && 
						form.customControlAuthoring().getValue().getAuthoringDateTimeIsNotNull() ? 
								form.customControlAuthoring().getValue().getAuthoringDateTime() : null);
			voAuthor.setAuthoringHcp(
					form.customControlAuthoring().getValue() != null &&
						form.customControlAuthoring().getValue().getAuthoringHcpIsNotNull() ? 
								form.customControlAuthoring().getValue().getAuthoringHcp() : null);
					
			if(voAuthor.getAuthoringDateTime()==null || voAuthor.getAuthoringHcp()==null)
				clinicalNotesVo.setAuthoringInfo(null);
			else
				clinicalNotesVo.setAuthoringInfo(voAuthor);
		}
		
		if (form.chkForReview().getValue())
		{
			clinicalNotesVo.setForReview(new Boolean(form.chkForReview().getValue()));
			clinicalNotesVo.setForReviewDiscipline(form.cmbDiscipline().getValue());
		}
		else
		{
			clinicalNotesVo.setForReview(null);
			clinicalNotesVo.setForReviewDiscipline(null);
		}
		
		if (form.iscustomControlReviewedVisible())
		{
			clinicalNotesVo.setReviewingDateTime(
					form.customControlReviewed().getValue() != null && 
						form.customControlReviewed().getValue().getAuthoringDateTimeIsNotNull() ? 
							form.customControlReviewed().getValue().getAuthoringDateTime() : null);
			clinicalNotesVo.setReviewingHCP(
					form.customControlReviewed().getValue() != null && 
						form.customControlReviewed().getValue().getAuthoringHcpIsNotNull() ? 
							form.customControlReviewed().getValue().getAuthoringHcp() : null);
		}
		
		if (clinicalNotesVo.getRecordingUser() == null)
			clinicalNotesVo.setRecordingUser((MemberOfStaffShortVo)domain.getMosUser());
		if (clinicalNotesVo.getRecordingDateTime() == null)
			clinicalNotesVo.setRecordingDateTime(new DateTime());

		if (form.richNotes().isVisible())//WDEV-14968
		{
			clinicalNotesVo.setClinicalNote(form.richNotes().getValue());
		}
		else
		{
			clinicalNotesVo.setClinicalNote(form.txtNotes().getValue());
		}
		
		if ( ! clinicalNotesVo.getNoteTypeIsNotNull())
			clinicalNotesVo.setNoteType(ClinicalNoteType.CLINICALNOTE);
		
		clinicalNotesVo.setIsDerivedNote(Boolean.FALSE);
		clinicalNotesVo.setSourceOfNote(SourceOfNote.CLINICALCLINICALNOTE);
		
				
		return clinicalNotesVo;
	}

	protected void showHideCustomComponent(IComponent customControl, Boolean isEnabled, boolean initialize)
	{	
		if (customControl != null)
		{
			customControl.setEnabledAuthoringHCP(isEnabled);
			customControl.setEnabledDateTime(isEnabled);
		}
		
		if (customControl != null &&
				initialize != false)
		{	
			customControl.initializeComponent();
		}
	}
	
	private MemberOfStaffShortVo getDisciplineForLoggedInUser(ClinicalNotesVo clinicalNotesVo)
	{
		MemberOfStaffVo fullVo = null;
		MemberOfStaffShortVo mos = (MemberOfStaffShortVo)domain.getMosUser();
		if (mos != null)
			fullVo = domain.getMemberOfStaff(mos);

		if (fullVo != null)
		{
			if (fullVo.getHcpIsNotNull() && fullVo.getHcp() instanceof MedicVo)
			{
				MedicVo voMedic = (MedicVo)fullVo.getHcp();
				if (voMedic.getHcpTypeIsNotNull())
					clinicalNotesVo.setDiscipline(voMedic.getHcpType());
				else
				{
					engine.showMessage("Please select a Discipline type for the logged in user.");
					return null;
				}
			}
			else
			{
				if (form.customControlAuthoring().getValue()!=null && form.customControlAuthoring().getValue().getAuthoringHcpIsNotNull()
					&& form.customControlAuthoring().getValue().getAuthoringHcp().getHcpTypeIsNotNull())
					clinicalNotesVo.setDiscipline(form.customControlAuthoring().getValue().getAuthoringHcp().getHcpType());
				else
				{ 
					if (form.getMode().equals(FormMode.EDIT))//WDEV-14967
					engine.showMessage("No Discipline is available. Please choose an authoring user.");
					return null;
				}
			}
		}
		else
		{
			engine.showMessage("Member of Staff is Null.");
			return null;
		}
		return mos;
	}
	
	private ClinicalNoteStatusVoCollection addStatusToCollection(ClinicalNoteStatusVoCollection statusHistory, ClinicalNoteStatusVo voStat) 
	{
		ClinicalNoteStatusVoCollection voColl = statusHistory;
		if (voColl == null)
			voColl = new ClinicalNoteStatusVoCollection();
		voColl.add(voStat);
		
		return voColl;
	}
	
	private boolean correctModeIP(ClinicalNoteStatusVo currentStatus) 
	{
		if (currentStatus != null &&
				currentStatus.getStatusIsNotNull() && 
					(currentStatus.getStatus().equals(ClinicalNotesStatus.ACTIVE) ||
						currentStatus.getStatus().equals(ClinicalNotesStatus.CORRECTED) ) && 
							domain.getHcpLiteUser() != null && 
								/*domain.getHcpLiteUser().equals(form.customControlAuthoring().getValue().getAuthoringHcp())*/
							testDiscipline())
			return true;
		else
			return false;
	}
	
	private boolean testDiscipline()
	{
		MemberOfStaffVo fullVo = null;
		MemberOfStaffShortVo mos = (MemberOfStaffShortVo)domain.getMosUser();
		if (mos != null)
			fullVo = domain.getMemberOfStaff(mos);
		
		if (fullVo != null)
		{
			if (fullVo.getHcpIsNotNull())
			{
				if (fullVo.getHcp().getHcpTypeIsNotNull())
				{
					if (form.customControlAuthoring().getValue() != null &&
							form.customControlAuthoring().getValue().getAuthoringHcpIsNotNull() &&
								form.customControlAuthoring().getValue().getAuthoringHcp().getHcpTypeIsNotNull())
					{
						if (form.customControlAuthoring().getValue().getAuthoringHcp().getHcpType().equals(fullVo.getHcp().getHcpType()))
							return true;
					}					
				}				
			}
		}
		return false;
	}
	
	protected void onBtnUpdateClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);
		
		showHideCustomComponent(form.customControlAuthoring(), Boolean.FALSE, false);
		
		form.richNotes().setEnabled(true);
		form.btnClose().setVisible(false);
		
		if (isDialog())
			form.getGlobalContext().Clinical.setReturnToFormMode(FormMode.EDIT);
		
		form.getGlobalContext().Core.setClinicalNotingMode(ClinicalNotingMode.UPDATE);
		if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull() &&
				validationIPMode(form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatus()))
		{
			form.getGlobalContext().Core.setClinicalNotingMode(ClinicalNotingMode.VALIDATE);
		}
	}
	
	private boolean validationIPMode(ClinicalNoteStatusVo currentStatus) 
	{
		if (currentStatus != null
			&&	currentStatus.getStatusIsNotNull() 
			&& (currentStatus.getStatus().equals(ClinicalNotesStatus.PREVALIDATION))
			&& domain.getHcpLiteUser() != null 
			/*&& domain.getHcpLiteUser().equals(form.customControlAuthoring().getValue().getAuthoringHcp())*/
			&& testDiscipline())
			return true;
		else
			return false;
	}
	
	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		newInstance();
	}
	
	private void newInstance() 
	{
		form.setMode(FormMode.EDIT);
		
		form.txtNotes().setVisible(false);//WDEV-14968
		form.txtNotes().setEnabled(false);
		
		form.richNotes().setEnabled(true);
		form.cmbStatus().setEnabled(true);
		form.customControlAuthoring().initializeComponent();
		
		form.customControlAuthoring().setEnabledAuthoringHCP(Boolean.TRUE);
		form.customControlAuthoring().setEnabledDateTime(Boolean.TRUE);
		
		AuthoringInformationVo voAuthoringInformation = new AuthoringInformationVo ();
		voAuthoringInformation.setAuthoringDateTime(new DateTime());
		if (domain.getHcpUser() != null)
		{
			HcpLiteVo authoringHcp = (HcpLiteVo) domain.getHcpLiteUser();
			if (authoringHcp != null)
				voAuthoringInformation.setAuthoringHcp(authoringHcp);
			form.customControlAuthoring().setValue(voAuthoringInformation);
			fillIPStatusNew();	
		}
		else // No a HCP
		{
			if (form.getGlobalContext().Core.getCurrentClinicalContactIsNotNull() && form.getGlobalContext().Core.getCurrentClinicalContact().getSeenByIsNotNull())
				voAuthoringInformation.setAuthoringHcp(form.getGlobalContext().Core.getCurrentClinicalContact().getSeenBy());
			form.customControlAuthoring().setValue(voAuthoringInformation);			
			fillIPStatusPreValidation();
		}

		
		if (form.customControlAuthoring().getValue() != null && 
				form.customControlAuthoring().getValue().getAuthoringHcpIsNotNull() && 
					form.customControlAuthoring().getValue().getAuthoringHcp().getHcpTypeIsNotNull())
						form.txtDiscipline().setValue(form.customControlAuthoring().getValue().getAuthoringHcp().getHcpType().getText());
		
		form.setcustomControlReviewedVisible(false);
		form.chkMarkAsReviewed().setVisible(false);

		form.btnClose().setEnabled(false);
		
	}

	private void setCurrentClinicalNote()
	{
		if (form.getGlobalContext().Core.getCurrentClinicalContactIsNotNull())
		{
			ClinicalContactShortVo currentClinicalContact = form.getGlobalContext().Core.getCurrentClinicalContact();
			ClinicalNotesVo clinicalNotesForContact = domain.getClinicalNotesForContact(currentClinicalContact);
			if (clinicalNotesForContact != null)
				form.getGlobalContext().Clinical.setCurrentClinicalNote(domain.getClinicalNote(clinicalNotesForContact));
			else
				form.getGlobalContext().Clinical.setCurrentClinicalNote(null);
		}
	}
	
	private void openNotingDetails() throws PresentationLogicException
	{
		clearDetails();
		form.setMode(FormMode.VIEW);
		
		//WDEV-7179 
		//if(ConfigFlag.UI.ALLOW_ONLY_ONE_CLINICAL_NOTE.getValue() && form.getGlobalContext().Clinical.getCurrentClinicalNote()==null)-comment from wdev-9693
		if(form.getGlobalContext().Core.getCurrentClinicalContactIsNotNull()&& form.getGlobalContext().Clinical.getCurrentClinicalNote()==null)
			setCurrentClinicalNote();
		//for RIE refresh the note
		if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull())
		{
			form.getGlobalContext().Clinical.setCurrentClinicalNote(domain.getClinicalNote(form.getGlobalContext().Clinical.getCurrentClinicalNote()));
		}
		
		form.getLocalContext().setclinicalNotesVo(form.getGlobalContext().Clinical.getCurrentClinicalNote());
		if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull() && isDialog()) //WDEV-15382 
		{
					
			if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getSourceOfNoteIsNotNull())
			{
				if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getSourceOfNote().equals(SourceOfNote.CLINICALCLINICALNOTE) )
					populateScreenControls(form.getGlobalContext().Clinical.getCurrentClinicalNote());
				else
					throw new FormOpenException("There is a clinical note of a different type already recorded on the system for this clincal contact");
			}
			
			populateScreenControls(form.getGlobalContext().Clinical.getCurrentClinicalNote());
			
			if (form.getGlobalContext().Clinical.getReturnToFormModeIsNotNull() &&
					form.getGlobalContext().Clinical.getReturnToFormMode().equals(FormMode.EDIT))
			{
				form.setMode(FormMode.EDIT);
				
				form.customControlAuthoring().setEnabledAuthoringHCP(Boolean.FALSE);
				form.customControlAuthoring().setEnabledDateTime(Boolean.FALSE);
				
				if(form.getGlobalContext().Core.getClinicalNotingModeIsNotNull() &&
					form.getGlobalContext().Core.getClinicalNotingMode().equals(ClinicalNotingMode.REVIEW))
					{
						form.chkForReview().setVisible(false);
						form.cmbDiscipline().setVisible(false);
						form.lblDiscipline().setVisible(false);
						form.cmbStatus().setEnabled(false);
						form.setcustomControlReviewedVisible(true);
						form.customControlReviewed().setLabels(AuthoringLabelType.REVIEWING);
						form.chkMarkAsReviewed().setVisible(true);
						form.chkMarkAsReviewed().setValue(true);
						onChkMarkAsReviewedValueChanged();
						
						form.richNotes().setEnabled(false);
				
						if (! form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingHCPIsNotNull() && 
								! form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingDateTimeIsNotNull())
						{
							enabledCustomReviewed(Boolean.TRUE);
						}
					}
				
				if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingHCPIsNotNull()
						&& form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingDateTimeIsNotNull())
				{
					enabledCustomReviewed(Boolean.FALSE);
					form.chkMarkAsReviewed().setEnabled(false);
					
					AuthoringInformationVo voAuthoringInformation = new AuthoringInformationVo();
					voAuthoringInformation.setAuthoringHcp(form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingHCP());
					voAuthoringInformation.setAuthoringDateTime(form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingDateTime());
					form.customControlReviewed().setValue(voAuthoringInformation);
					form.cmbStatus().setEnabled(true);
					form.richNotes().setEnabled(true);
					form.txtNotes().setEnabled(true);//WDEV-14968
				}
				
				form.btnClose().setVisible(false);
				
				if (form.chkForReview().isVisible())
				{
					form.richNotes().setEnabled(true);
					form.cmbStatus().setEnabled(true);
					form.txtNotes().setEnabled(true);//WDEV-14968
				}
			}
			else
			{
				ClinicalNotesVo note = form.getGlobalContext().Clinical.getCurrentClinicalNote();
				boolean isDraft = note.getCurrentStatusIsNotNull() && ClinicalNotesStatus.DRAFT.equals(note.getCurrentStatus().getStatus());
				boolean isMine = note.getAuthoringInfoIsNotNull() && note.getAuthoringInfo().getAuthoringHcpIsNotNull() 
									&& note.getAuthoringInfo().getAuthoringHcp().equals(domain.getHcpLiteUser());
				setBtnEdit((isDraft && isMine) || !isDraft);
				setBtnNew(false);
			}
		}	
		else 
			if (form.getGlobalContext().Clinical.getCurrentClinicalNote() == null &&
					form.getGlobalContext().Clinical.getReturnToFormModeIsNotNull() && 
						form.getGlobalContext().Clinical.getReturnToFormMode().equals(FormMode.EDIT) )
			{
				newInstance();
			
				form.customControlAuthoring().setEnabledAuthoringHCP(Boolean.TRUE);
				form.customControlAuthoring().setEnabledDateTime(Boolean.TRUE);

				form.getGlobalContext().Clinical.setReturnToFormMode(null);
				form.getGlobalContext().Clinical.setCurrentClinicalNote(null);
			}
			else
			{
				form.customControlAuthoring().setEnabledAuthoringHCP(Boolean.FALSE);
				form.customControlAuthoring().setEnabledDateTime(Boolean.FALSE);
			
				if (form.getGlobalContext().Core.getCurrentClinicalContactIsNotNull())
				{
					 ClinicalNotesVoCollection voNoteCollection = domain.getClinicalNotes(form.getGlobalContext().Core.getCurrentClinicalContact());
					 ClinicalNotesVo voNote = null;
					 
					 if (voNoteCollection != null && voNoteCollection.size() > 0)  //WDEV-15382
						  voNote =  voNoteCollection.get(0);
					
					if (voNote != null && voNote.getNoteType() != null && voNote.getNoteType().equals(ClinicalNoteType.CLINICALNOTE))
					{
						populateScreenControls(voNote);
						boolean isDraft = voNote.getCurrentStatusIsNotNull() && ClinicalNotesStatus.DRAFT.equals(voNote.getCurrentStatus().getStatus());
						boolean isMine = voNote.getAuthoringInfoIsNotNull() && voNote.getAuthoringInfo().getAuthoringHcpIsNotNull() 
											&& voNote.getAuthoringInfo().getAuthoringHcp().equals(domain.getHcpLiteUser());
						setBtnEdit((isDraft && !isMine) || !isDraft);
						setBtnNew(false);
					}
					else
					{
						setBtnNew(true);
						setBtnEdit(false);
					}
				}
				else
				{
					setBtnEdit(false);
					setBtnNew(false);
				}
			}
		
		
	}

	private void setBtnNew(boolean value)
	{
		form.btnNew().setVisible(value);
		form.btnNew().setEnabled(value);
	}

	private void setBtnEdit(boolean value)
	{
		form.btnUpdate().setVisible(value);
		form.btnUpdate().setEnabled(value);
	}

	private void enabledCustomReviewed(Boolean value)
	{
		form.customControlReviewed().setEnabledAuthoringHCP(value);
		form.customControlReviewed().setEnabledDateTime(value);
	}
	
	private void enableCustomReviewed(boolean isEnabled)
	{
		if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingHCPIsNotNull()
				&& form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingDateTimeIsNotNull())
		{
			if (isEnabled == false)
				enabledCustomReviewed(Boolean.FALSE);
			else
				enabledCustomReviewed(Boolean.TRUE);
				
			form.chkMarkAsReviewed().setEnabled(isEnabled);
			setReviewedInfo();
		}
	}
	
	private void populateScreenControls(ClinicalNotesVo voNote) throws FormOpenException 
	{
		if (voNote.getIsDerivedNoteIsNotNull() 
				&& voNote.getIsDerivedNote().booleanValue())
					throw new FormOpenException("There is a clinical note of a different type already recorded on the system for this clincal contact");
		
		
		form.getLocalContext().setclinicalNotesVo(voNote);
		
		settingCustomAuthoring(voNote);

		if (voNote.getClinicalNote().startsWith("<!-- _ims_rich_text_control")) //WDEV-14968
		{
			form.txtNotes().setVisible(false);
			form.richNotes().setVisible(true);
			form.richNotes().setEnabled(false);
			form.richNotes().setValue(voNote.getClinicalNote());
		}
		else 
		{
			form.richNotes().setVisible(false);
			form.txtNotes().setVisible(true);
			form.txtNotes().setEnabled(false);
			form.txtNotes().setValue(voNote.getClinicalNote());
		}
		
		form.txtDiscipline().setValue(voNote.getDisciplineIsNotNull() ? voNote.getDiscipline().getText() : "");//wdev-8976

		if (voNote.getForReviewIsNotNull() && voNote.getForReview().booleanValue())
		{
			form.chkForReview().setValue(voNote.getForReview().booleanValue());
			form.cmbDiscipline().setValue(voNote.getForReviewDiscipline());

			form.chkForReview().setVisible(true);
			form.cmbDiscipline().setVisible(true);
			form.lblDiscipline().setVisible(true);
			form.setcustomControlReviewedVisible(false);
			form.chkMarkAsReviewed().setVisible(false);
			
			if (voNote.getReviewingHCPIsNotNull() || voNote.getReviewingDateTimeIsNotNull())
			{
				settingCustomReviewed(voNote);
				
				form.chkForReview().setVisible(false);
				form.cmbDiscipline().setVisible(false);
				form.lblDiscipline().setVisible(false);
				form.setcustomControlReviewedVisible(true);
				form.customControlReviewed().setLabels(AuthoringLabelType.REVIEWING);
				form.chkMarkAsReviewed().setVisible(true);
				form.chkMarkAsReviewed().setValue(true);
			}
		}
		
		setCmbStatus(voNote);
		
		
	}

	private void setCmbStatus(ClinicalNotesVo voNote)
	{
		fillIPStatusCombo(voNote);
		
		if (form.cmbStatus().getValues().size() == 0 &&
				voNote.getCurrentStatus().getStatusIsNotNull())
			form.cmbStatus().newRow(voNote.getCurrentStatus().getStatus(), voNote.getCurrentStatus().getStatus().getText());
		
		form.cmbStatus().setValue(voNote.getCurrentStatusIsNotNull() ? voNote.getCurrentStatus().getStatus() : null);
	}

	private void settingCustomReviewed(ClinicalNotesVo voNote)
	{
		AuthoringInformationVo voReview = new AuthoringInformationVo();
		voReview.setAuthoringDateTime(voNote.getReviewingDateTime());
		voReview.setAuthoringHcp(voNote.getReviewingHCP());
		form.customControlReviewed().setValue(voReview);
	}

	private void settingCustomAuthoring(ClinicalNotesVo voNote)
	{
		AuthoringInformationVo voAuthor = new AuthoringInformationVo();
		voAuthor.setAuthoringDateTime(voNote.getAuthoringInfoIsNotNull() ? voNote.getAuthoringInfo().getAuthoringDateTime() : null);
		voAuthor.setAuthoringHcp(voNote.getAuthoringInfoIsNotNull() ? voNote.getAuthoringInfo().getAuthoringHcp() : null);
		form.customControlAuthoring().setValue(voAuthor);
	}

	private void clearDetails() 
	{
		form.customControlAuthoring().setValue(null);
		form.txtDiscipline().setValue(null);
		form.richNotes().setValue(null);
		form.cmbStatus().setValue(null);
		form.customControlReviewed().setValue(null);
		form.chkForReview().setValue(false);
		form.cmbDiscipline().setValue(null);
		form.txtNotes().setValue(null);//WDEV-14968
	}
	
	protected void onBtnCloseClick() throws PresentationLogicException 
	{
		form.getGlobalContext().Core.setClinicalNotingMode(null);
		engine.close(DialogResult.OK);
		
	}

	protected void onCustomControlAuthoringValueChanged() throws PresentationLogicException
	{
		if(form.customControlAuthoring().getValue()!=null)
			form.txtDiscipline().setValue(form.customControlAuthoring().getValue().getAuthoringHcpIsNotNull()
					&& form.customControlAuthoring().getValue().getAuthoringHcp().getHcpTypeIsNotNull() ? form.customControlAuthoring().getValue().getAuthoringHcp().getHcpType().getText() : "");
		else
			form.txtDiscipline().setValue("");
	}

	protected void onChkForReviewValueChanged() throws PresentationLogicException
	{
		if (form.chkForReview().getValue() == true)
		{
			form.cmbDiscipline().setEnabled(true);
		}
		else
		{
			form.cmbDiscipline().setEnabled(false);
			form.cmbDiscipline().setValue(null);
		}
	}

	protected void onChkMarkAsReviewedValueChanged() throws PresentationLogicException
	{
		if (form.chkMarkAsReviewed().getValue() == true)
		{
			enabledCustomReviewed(Boolean.TRUE);
			form.customControlReviewed().initializeComponent();
		}
		else
		{
			enabledCustomReviewed(Boolean.FALSE);	
			form.customControlReviewed().setValue(null);
		}	
	}

	protected void onFormModeChanged()
	{
		form.chkForReview().setEnabled(form.getMode().equals(FormMode.EDIT) ? true : false);
		form.cmbDiscipline().setEnabled(form.getMode().equals(FormMode.EDIT) ? true : false);
		
		if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull())
		{
			form.setcustomControlReviewedEnabled(form.getMode().equals(FormMode.EDIT) ? true : false);
			form.chkMarkAsReviewed().setEnabled(form.getMode().equals(FormMode.EDIT) ? true : false);
		}
		if (form.getMode().equals(FormMode.EDIT))
		{
			//In Correct mode
			if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull() &&
					form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatusIsNotNull() &&
						correctModeIP(form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatus()) &&
							form.getGlobalContext().Clinical.getCurrentClinicalNote().getForReviewDisciplineIsNotNull())
						{
							form.chkForReview().setEnabled(false);
							form.cmbDiscipline().setEnabled(false);
							form.cmbStatus().setEnabled(false);
						}
			else
			{
				form.chkForReview().setEnabled(true);
				
				if (form.chkForReview().getValue() == false)
					form.cmbDiscipline().setEnabled(false);
				else
					form.cmbDiscipline().setEnabled(true);
				
				form.cmbStatus().setEnabled(true);
				
				if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull() &&
						form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatusIsNotNull() 
						&&  form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatus().getStatusIsNotNull()
						&&  form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatus().getStatus().equals(ClinicalNotesStatus.PREVALIDATION) )
				{
					form.cmbStatus().setEnabled(false);
				}
				else
					form.cmbStatus().setEnabled(true);

			}
		}
		
		if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull())
		{
			form.setcustomControlReviewedEnabled(form.getMode().equals(FormMode.EDIT) ? true : false);
			form.chkMarkAsReviewed().setEnabled(form.getMode().equals(FormMode.EDIT) ? true : false);
			
			enableCustomReviewed(false);
		}

	}
	
	private void checkForDiscipline()
	{
		if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull())
		{
			MemberOfStaffShortVo mos = null;
			if (getDisciplineForLoggedInUser(form.getGlobalContext().Clinical.getCurrentClinicalNote()) != null)
				mos = getDisciplineForLoggedInUser(form.getGlobalContext().Clinical.getCurrentClinicalNote());
			else
			{
				//engine.showMessage("No Discipline is available. Please choose an authoring user."); WDEV-14967
				return;
			}
					
			/*if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull())
				{
				if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatusIsNotNull() &&
						form.getGlobalContext().Clinical.getCurrentClinicalNote().getDisciplineIsNotNull() &&
						( ( mos.getHcpIsNotNull() &&
							!form.getGlobalContext().Clinical.getCurrentClinicalNote().getAuthoringInfo().getAuthoringHcp().getHcpType().equals(mos.getHcp().getHcpType()) &&
								form.getGlobalContext().Clinical.getReturnToFormModeIsNotNull() &&
									!form.getGlobalContext().Clinical.getReturnToFormMode().equals(FormMode.EDIT) ) ||
										mos.getHcpIsNotNull() ))
								{
									form.btnNew().setVisible(false);
									form.btnUpdate().setVisible(false);
								}
				}*/
			
			if (form.getGlobalContext().Clinical.getCurrentClinicalNoteIsNotNull())// &&
				//	form.getGlobalContext().Clinical.getCurrentClinicalNote().getIsTranscribedIsNotNull() )
					{
						if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatusIsNotNull() &&
								form.getGlobalContext().Clinical.getCurrentClinicalNote().getDisciplineIsNotNull() &&
									mos.getHcpIsNotNull())
						{
									if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getAuthoringInfoIsNotNull() &&
											form.getGlobalContext().Clinical.getCurrentClinicalNote().getAuthoringInfo().getAuthoringHcpIsNotNull() &&
											!form.getGlobalContext().Clinical.getCurrentClinicalNote().getAuthoringInfo().getAuthoringHcp().getHcpType().equals(mos.getHcp().getHcpType()) &&
										(form.getGlobalContext().Clinical.getReturnToFormModeIsNotNull() &&
											!form.getGlobalContext().Clinical.getReturnToFormMode().equals(FormMode.EDIT) ||
											form.getGlobalContext().Clinical.getReturnToFormMode() == null))
			
									{
										form.btnNew().setVisible(false);
										form.btnUpdate().setVisible(false);
									}
						}
						//Non HCP
						else 
						{
							if (form.getMode().equals(FormMode.VIEW) &&
									domain.getHcpLiteUser() == null)
							{
								form.btnNew().setVisible(false);
								form.btnUpdate().setVisible(false);
								
								if (form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatusIsNotNull() &&
										form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatus().getStatusIsNotNull() &&
											!(form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatus().getStatus().equals(ClinicalNotesStatus.ACTIVE) ||
												form.getGlobalContext().Clinical.getCurrentClinicalNote().getCurrentStatus().getStatus().equals(ClinicalNotesStatus.CORRECTED)))
								{
									form.btnUpdate().setVisible(true);
								}
							}
						}
				}
		}
	}
	
	private void setReviewedInfo()
	{
		AuthoringInformationVo voAuthoringInformation = new AuthoringInformationVo();
		voAuthoringInformation.setAuthoringHcp(form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingHCP());
		voAuthoringInformation.setAuthoringDateTime(form.getGlobalContext().Clinical.getCurrentClinicalNote().getReviewingDateTime());
		form.customControlReviewed().setValue(voAuthoringInformation);
	}
	
	private void fillIPStatusCombo(ClinicalNotesVo voClinicalNote) 
	{
		if (voClinicalNote != null)
		{
			//In Correct mode, HCP ok and either Active or Correct
			if (correctModeIP(voClinicalNote.getCurrentStatus())) 
			{
				form.btnUpdate().setText("Correct");
				fillIPStatusCorrect(); 
			}
			//Requires Validation
			else if (voClinicalNote.getCurrentStatus().getStatusIsNotNull() &&
				voClinicalNote.getCurrentStatus().getStatus().equals(ClinicalNotesStatus.PREVALIDATION))
			{
				//fillIPStatusValidation();
				if (domain.getHcpLiteUser() != null)
					form.btnUpdate().setText("Validate");
				fillIPStatusPreValidation();
			}
			//Draft, HCP OK
			else if (voClinicalNote.getCurrentStatus().getStatusIsNotNull() &&
				voClinicalNote.getCurrentStatus().getStatus().equals(ClinicalNotesStatus.DRAFT)	&&
					domain.getHcpLiteUser() != null	&&
						//domain.getHcpLiteUser().equals(form.customControlAuthoring().getValue().getAuthoringHcp())
					testDiscipline())
			{
				fillIPStatusNew();
			}
			//Draft, HCP not OK
			else if (voClinicalNote.getCurrentStatus().getStatusIsNotNull()	&&
				voClinicalNote.getCurrentStatus().getStatus().equals(ClinicalNotesStatus.DRAFT)	&&
					domain.getHcpLiteUser() == null) 
			{
				fillIPStatusPreValidation();
			}				
		}
	}
	
	private void fillIPStatusPreValidation() 
	{
		form.cmbStatus().clear();
		form.cmbStatus().newRow(ClinicalNotesStatus.PREVALIDATION, ClinicalNotesStatus.PREVALIDATION.getText());
		form.cmbStatus().newRow(ClinicalNotesStatus.DRAFT, ClinicalNotesStatus.DRAFT.getText());
	}

	private void fillIPStatusNew() 
	{
		form.cmbStatus().clear();
		form.cmbStatus().newRow(ClinicalNotesStatus.ACTIVE, ClinicalNotesStatus.ACTIVE.getText());
		form.cmbStatus().newRow(ClinicalNotesStatus.DRAFT, ClinicalNotesStatus.DRAFT.getText());
		form.cmbStatus().setValue(ClinicalNotesStatus.ACTIVE);//wdev-9362
	}

	private void fillIPStatusCorrect() 
	{
		form.cmbStatus().clear();
		form.cmbStatus().newRow(ClinicalNotesStatus.ACTIVE, ClinicalNotesStatus.ACTIVE.getText());
		form.cmbStatus().newRow(ClinicalNotesStatus.CORRECTED, ClinicalNotesStatus.CORRECTED.getText());
	}
	
}
