
/*
 * Call the Spire chemotherapy appointments interface.
 * 
 * This is tightly coupled with the Form Editor definition for form 'SCR Post Treatment Pathway', ChemoF24
 * as there are explicit references to the fields defined in the form.
 * We obtain an appointment date entered by the user in this form, then call a local Controller to initiate communication with Mirth interface via REST,
 * which hopefully returns the results via JSON.
 * Note that the relevant patient and hospital is obtained from the current user Session.
 * 
 * If the appointments interface returns multiple appointments which match the specified date, a dialog box will be constructed dynamically so the user can select the one they want.
 * 
 * Paul Barratt
 * 07 Dec 2017
 * 
 */
// global copy of message from feed REST response, used in the dialog box event handler
let theMsg;
let nIntervId;
const resultPollingInterval = 500;
//main entry point, called from command button on form via mechanism in userFunctionLibrary.jsp
function appointmentsLookup(){
	let urlToCall = "../emdt/fetchChemoAppointments.form";
	const apptDateControl = document.getElementById("CF24S1Date");
	if (! apptDateControl)	{
		alert("Problem with appointments lookup: unable to find expected date field 'CF24S1Date'. Perhaps form design has been modified?");
		return;
	}
	let apptDate = apptDateControl.value;
	urlToCall += "?appointmentDate=" + apptDate;
	$.ajax({
		type: "POST",
		method: "POST",
		data: $("#consultationNote").serialize(),
		url:  urlToCall,
		success : function(msg) {
			if(msg.status){
				showProgress();
				nIntervId=setInterval(checkChemoResult, resultPollingInterval, msg.chemoAppointmentId)
				setInfoMessage("Waiting for response from Spire..");
			}
			if(msg.errorMsg && msg.errorMsg !== ""){
				setErrorMessage(msg.errorMsg);
				// alert(msg.errorMsg);
			}
		},
		error: function(msg){
			setErrorMessage(msg.errorMsg);
			// alert("There was a problem fetching the appointments.");
		}
	});
}
function checkChemoResult(chemoAppointmentId)	{
	$.ajax({
		type : "GET",
		url : "../emdt/checkChemoAppointmentsResult.form",
		data : "chemoAppointmentId="+chemoAppointmentId,
		success : function(msg) {
			if(msg.status==='completed'){
				clearInterval(nIntervId);
				hideProgress();
				if (msg.errorMsg && msg.errorMsg !== "")	{
					setErrorMessage(msg.errorMsg);
				}else{
					let appointmentIndex = -1;	// sentinel
					if (msg.numAppointments === 1)	{
						appointmentIndex = 0;
					}else	{
						// multiple appointments were returned: dynamically create and show dialog to let user select one
						theMsg = msg;
						showChooseAppointmentDialog (msg.appointments);
						appointmentIndex = 0;
					}
					if (appointmentIndex === -1)
						return;
					let appointment = msg.appointments[appointmentIndex];
					populateFormFromAppointment (appointment);
					setInfoMessage("Completed");
				}
			}
		},
		error: function(msg){
			setErrorMessage(msg);
		}

	});
}
function showProgress(){
	$("#button_run").hide();
	$("#button_wait_run").show();
}

function hideProgress()	{
	$("#button_wait_run").hide();
	$("#button_run").show();
}

function setInfoMessage (message)	{
	console.info(message);
	$("#status_message").html(message).addClass("info").removeClass("error");
}

function setErrorMessage (message)	{
	console.error(message);
	$("#status_message").html(message).addClass("error").removeClass("info");
}

// Populate the form fields from the appointment data in the JSON
function populateFormFromAppointment (appointment)	{
	let ctlname;
	let serviceNum;
	let val = "";
	setval("CF24S1CaseNumber", appointment.caseNumber);
	setval("CF24S1DrugRegimen", appointment.drugRegimen);
	// loop through the chemo services.  there should be up to 16 of these
	const maxServices = Math.min(16, appointment.chemoServicesList.length);
	let i;
	for (i = 0; i <= maxServices-1; i++)	{
		serviceNum = 1 + i;
		ctlname = "CF24S1Service" + serviceNum;
		val = appointment.chemoServicesList[i].description;
		setval(ctlname, val);
	}
	// clear boxes any not present in feed data
	for (i = maxServices; i < 16; i++)	{
		serviceNum = 1 + i;
		ctlname = "CF24S1Service" + serviceNum;
		setval(ctlname, "");
	}
	// do the diagnoses.  there should be 1 or 2 of these.
	setval("CF24S1Diagnosis1", "");
	setval("CF24S1Diagnosis2", "");
	if (appointment.diagnosisList)
		if (appointment.diagnosisList.length >= 1)	{
			val = appointment.diagnosisList[0].code + " " + appointment.diagnosisList[0].description;
			setval("CF24S1Diagnosis1", val);
		}
	if (appointment.diagnosisList.length >= 2)	{
		val = appointment.diagnosisList[1].code + " " + appointment.diagnosisList[1].description;
		setval("CF24S1Diagnosis2", val);
	}

}

let dialogbox;
let parentContainer;

function closeDialog ()	{
	console.log("close dialog");
	parentContainer.removeChild (dialogbox);
	dialogbox = null;
	return false;
}

function clicker_handler (e)	{
	if(!e) {
		e = event;
	}
	const o = e.target || e.srcElement;

	if (!o)
		return;
	const i = o.value;
	populateFormFromAppointment (theMsg.appointments[i]);
}
// Dynamically create a little form showing the user the multiple appointments returned.  
// form will show radio buttons for each appointment contained.
// Let user choose which one they want via radio buttons.
function showChooseAppointmentDialog (appointmentsList)	{
	const apptDateControl = document.getElementById("CF24S1Date");	// the date field is used as an anchor to create the dialog box nearby.
	parentContainer = apptDateControl.parentNode;
	const dialogDivName = "apptSelectionDiv";
	const mydiv = document.getElementById(dialogDivName);

	if (mydiv)	{
		parentContainer.removeChild(mydiv);
		dialogbox = null;
	}
	dialogbox = document.createElement("div");
	dialogbox.id = dialogDivName;
	const myform = document.createElement("form");
	dialogbox.appendChild (myform);
	const fs = document.createElement("fieldset");
	fs.style.backgroundColor = "lightyellow";
	myform.appendChild (fs);
	const leg = document.createElement("legend");
	leg.appendChild( document.createTextNode("Please select appointment date:") );
	fs.appendChild ( leg );
	const numAppt = appointmentsList.length;
	for (i = 0; i < numAppt; i++)	{
		let rb = document.createElement("input");
		rb.name = "apt_select_radio";
		rb.setAttribute("type", "radio");
		rb.setAttribute("value", i);
		if (i === 0)
			rb.setAttribute("checked", "checked");
		rb.id = "aptNum_" + i;
		rb.onchange = function() {clicker_handler(); };
		fs.appendChild(rb);
		const dt = appointmentsList[i].appointmentDateString;
		let lbl = document.createElement("label");
		lbl.setAttribute("for", rb.id);
		lbl.appendChild( document.createTextNode(" Date: " + dt + ", Case number:  " + appointmentsList[i].caseNumber))
		lbl.appendChild( document.createElement("br"));
		fs.appendChild( lbl );
	}
	let btn = document.createElement("button");
	btn.appendChild( document.createTextNode("Close") );
	btn.onclick = function() { closeDialog(); };
	fs.appendChild( btn );
	
	parentContainer.appendChild(dialogbox);
	
	return 0;
}
// helper to find control by ID, set value if control is found
function setval (controlName, newValue)		{
	let ctl = document.getElementById(controlName);
	if (ctl)
		ctl.value = newValue;
}