//all functions are based off of participantManager (print, config, etc.)
var participantIdManager={};

participantIdManager.set=
function(parentClass){
   this.parent=parentClass;
}

participantIdManager.addSelectOptions=
function(pM){
   if (pM.mode=="LOCAL") return;
   
   let input=this.getInputElement(pM);
   let config=this.parent.config;

   let fName='addParticipantSelectOptions';
   this.parent.print(fName+' input '+input);
   let opt=config.document.createElement("option");
   opt.value=-1;

   opt.text="<Select>";
   input.options[input.options.length]=opt;

   //here the lookup is being populated (registrationData)
   let demoRows=config.formConfig['registrationData'].rows;
   this.parent.print(fName+" demoRows: "+demoRows.length);
   for (let i=0;i<demoRows.length;i++){
      let opt2=config.document.createElement("option");
      opt2.value=i+1;
      let id=demoRows[i][this.getCrfEntryFieldName(pM)];
      let loc=demoRows[i][this.getCrfEntryFieldName(pM,'LOCAL')];
      opt2.text=id+' (Local: '+loc+')';
      input.options[input.options.length]=opt2;
      this.parent.print(fName+' '+pM.participantField+' '+demoRows[i][pM.participantField]);
   }

   input.selectedIndex=0;
}

participantIdManager.updateElements=
function(pM){
   let fName='[updateElements]';
   //reset all values (some might be different depending on the call timing)

   //selector is with study
   pM.cellSelector=this.parent.getElement(pM.cellSelectorId);
   pM.inputSelector=this.parent.getElement(pM.inputSelectorId);
   pM.textStudy=this.parent.getElement(pM.textStudyId);
  
   this.parent.print(fName+' selector '+pM.inputSelector+' id '+pM.inputSelectorId);
   //value is with local
   pM.cellValue=this.parent.getElement(pM.cellValueId);
   pM.inputValue=this.parent.getElement(pM.inputValueId);
   pM.textLocal=this.parent.getElement(pM.textLocalId);
   
   //pM.inputManageLocal=this.parent.getElement(pM.inputManageLocalId);
   //pM.inputManageStudy=this.parent.getElement(pM.inputManageStudyId);
}


participantIdManager.generateEntryField=
function(pM){
   let fName='[generateParticipantEntryField]:';
   this.parent.print(fName);

   //this is HTML designator of area on page
	let formName=this.parent.config.masterForm;

    
   pM.tb=this.parent.config.document.createElement('table');
   let tb=pM.tb;
	tb.className='t2';
	let row=tb.insertRow();
	
   //label for local ID
   let cell=this.parent.config.document.createElement('th');
	row.appendChild(cell);	
	cell.setAttribute("colspan","1");
	cell.style.fontSize="20px";
	cell.style.textAlign="left";
   //Use study coding for participant field
   cell.innerText='Local ID';
	//cell.innerText=pM.participantField;


   //value
   let cellValue=row.insertCell();
   cellValue.id=pM.cellValueId;

   pM.cellManageLocal=row.insertCell();
   
   //second row for study id
   let rowStudy=tb.insertRow();

   //label for study ID
   let cellStudy=this.parent.config.document.createElement('th');
	rowStudy.appendChild(cellStudy);	
	cellStudy.setAttribute("colspan","1");
	cellStudy.style.fontSize="20px";
	cellStudy.style.textAlign="left";
   //Use study coding for participant field
   cellStudy.innerText='Study ID';

	//selector for study id
   let cellSelector=rowStudy.insertCell();
   cellSelector.id=pM.cellSelectorId;

   //manage
   pM.cellManageStudy=rowStudy.insertCell();
   this.parent.getElement(formName).appendChild(tb);
   this.parent.print(fName+' done');

}


participantIdManager.getMode=
function(pM,mode="NONE"){
   if (mode=="NONE") return pM.mode;
   return mode;
}

//reslovers which operate depending on mode
participantIdManager.getInputId=
function(pM,mode="NONE"){
   let fName='[getInputId]';
   this.parent.print(fName);
   if (this.getMode(pM,mode)=="LOCAL") return pM.inputValueId;
   return pM.inputSelectorId;
}


participantIdManager.getInputCell=
function(pM,mode="NONE"){
   let fName='[getInputCell]';
   this.parent.print(fName+' mode '+mode+' getMode '+this.getMode(pM,mode));
   if (this.getMode(pM,mode)=="LOCAL") return pM.cellValue;
   return pM.cellSelector;
}

participantIdManager.getInputElement=
function(pM,mode="NONE"){
   let fName='[getInputElement]';
   this.parent.print(fName);
   let elementType=this.getInputElementType(pM,mode);
   let id=this.getInputId(pM,mode);
   let cell=this.getInputCell(pM,mode);
   let el=this.parent.getElement(id);
   this.parent.print(fName+' mode '+this.getMode(pM,mode)+' type '+elementType+' id '+id+' cell '+cell+' el '+el);
   if (el) return el;

   el=this.parent.config.document.createElement(elementType);
   this.parent.print(fName+' input '+el);
   el.id=id;

   cell.replaceChildren(el);
   this.addSelectOptions(pM);
 
   return el;
}

participantIdManager.getInputElementType=
function(pM,mode="NONE"){
   let fName='[getInputElementType]';
   this.parent.print(fName);
   if (this.getMode(pM,mode)=="LOCAL") return "input";
   return "select";
}


participantIdManager.getTextFieldId=
function(pM,mode="NONE"){
   let fName='[getTextFieldId]';
   this.parent.print(fName);
   if (this.getMode(pM,mode)=="LOCAL") return pM.textLocalId;
   return pM.textStudyId;
}

  
participantIdManager.getTextElement=
function(pM,mode="NONE"){
   let fName='[getTextElement]';
   this.parent.print(fName+' mode '+mode);
   let id=this.getTextFieldId(pM,mode);
   this.parent.print(fName+' id '+id);
   let el=this.parent.getElement(id);
   this.parent.print(fName+' el '+el);
   if (el) return el;
   el=this.parent.config.document.createElement("p");
   el.id=id;
   let cell=this.getInputCell(pM,mode);
   //let oldEl=pM.getInputElement(mode);
   cell.replaceChildren(el);
   return el;
}


//get the button, create if not there yet
participantIdManager.getInputManage=
function(pM,mode="NONE"){
   let fName='[getInputManage]';
   //this.parent.print(fName);
   //this prevents from having two inputs; it is either local or global from the outset
   if ("inputManage" in pM) return pM.inputManage;

   pM.inputManage=this.parent.config.document.createElement("input");
   let inputManage=pM.inputManage;
   inputManage.type="button";
   let that=this;
   inputManage.onclick=function(){that.manageId(pM);};
   //inputManageLocal.id=pM.inputManageLocalId;
   let cell=pM.cellManageStudy;
   if (this.getMode(pM,mode)=="LOCAL") cell=pM.cellManageLocal;
   //this.parent.print(fName+' inputManage '+pM.inputManage+' cell '+cell+' mode '+pM.mode);
   cell.appendChild(inputManage);
   return inputManage;
}

//callback that splits to edit or set/label mode

participantIdManager.manageId=
function(pM){
   let fName='[manageId]';
   this.parent.print(fName);
   //this can happen after object was created, so make sure current
   //elements are used
   this.updateElements(pM);
   let x=this.getInputManage(pM);

   if (x.value=="Set"){
      this.setId(pM);
      return;
   }
   if (x.value=="Edit"){
      this.editId(pM);
      return;
   }
}

//set mode
participantIdManager.setId=
function(pM){
   this.parent.print(fName);
   let el=this.getInputElement(pM);

   this.parent.print(fName+" value: "+el.value);
   let pId=el.value;
   let label=pId;
   if (pM.mode!="LOCAL"){
      if (el.value<0) return;
      let opt=el.options[el.selectedIndex];
      label=opt.text;
      pId=label.replace(/\(.*\)/,'');
      label=label.replace(/ \(Local: /,':');
      label=label.replace(/\)/,'');
   }
   this.setParticipantIdToCrfEntry(pM,pId);//no argument (should come from mode)
   this.parent.print(fName+" new value "+pId);
   this.setLabelMode(pM,label);
   pM.updateCrfEntry();
}

participantIdManager.setLabelMode=
function(pM,pId){
   let fName='[setLabelMode1]';

   this.parent.print(fName+' id '+pId);
   ids=pId.split(':');

   let textValue=this.getTextElement(pM);
   this.parent.print(fName+' textElement '+textValue);
   textValue.innerText=ids[0];

   if (pM.mode=="STUDY"){
      let loc=ids[1];
      //pM.getParticipantIdFromCrfEntry('LOCAL');
      this.parent.print(fName+' setting local id '+loc);
      let tValLocal=this.getTextElement(pM,'LOCAL');
      tValLocal.innerText=loc;
      this.setParticipantIdToCrfEntry(pM,loc,'LOCAL');
   }

   let x=this.getInputManage(pM);//getInputManage
   if ("readOnly" in pM){
      x.style.display="none";
   }
   x.value="Edit";

   
}

//edit mode
participantIdManager.editId=
function(pM){
   this.setEditMode(pM);
}


participantIdManager.setEditMode=
function(pM){

   let fName='[setEditMode1]';
   this.parent.print(fName+' pM '+pM+' mode '+pM.mode);
   //input
   let el=this.getInputElement(pM);

   let x=this.getInputManage(pM);
   x.value="Set";

}

//manage interaction to storage/CRF and study/LabKey
participantIdManager.getParticipantField=
function(){
   return this.parent.config.formConfig['studyDataAll'].rows[0]['SubjectColumnName'];
}

participantIdManager.getCrfEntryFieldName=
function(pM,mode="NONE"){
   let variable="Study";
   if (mode=="NONE") mode=pM.mode;
   if (mode=="LOCAL") variable="Local";
   return 'participant'+variable+'Id';
}

participantIdManager.setParticipantIdToCrfEntry=
function(pM,pId,mode="NONE"){
   this.parent.config.formConfig.crfEntry[this.getCrfEntryFieldName(pM,mode)]=pId;
}

participantIdManager.getParticipantIdFromCrfEntry=
function(pM,mode="NONE"){
   return this.parent.config.formConfig.crfEntry[this.getCrfEntryFieldName(pM,mode)];
}

participantIdManager.verifyCrfStudyId=
function(pM){

   //is studyId already set for the crf
   let studyId=this.getParticipantIdFromCrfEntry(pM,'STUDY');
   if (!studyId) return;
   pM.mode="STUDY";
   pM.readOnly="TRUE";
}

participantIdManager.verifyRegistration=
function(pM, formConfig){
   //if registration is in, 
   //then local id should not be changed any longer
   let idFieldName=this.getCrfEntryFieldName(pM,"STUDY");
   //let fQuery=config.formConfig.registrationData;
   let fQuery=formConfig.registrationData;
   if (fQuery.rows.length==0) return; //registration is empty

   let studyId=fQuery.rows[0][idFieldName];
   if (!studyId) return; //study id not set
   //set 
   pM.mode="STUDY";
   pM.readOnly="TRUE";
   //set crf (this happens later, but probably before the form will be corrected)
   this.setParticipantIdToCrfEntry(pM,studyId,"STUDY");
   pM.updateCrfEntry();
}


//main interface. Use this to generate object and to refer to it later on
participantIdManager.getObject=
function(){

   let fName='[getParticipantManagerObject]';
   this.parent.print(fName);

   let pM=new Object();

   //this never change
   pM.participantField=this.getParticipantField();


   pM.cellSelectorId=pM.participantField+"_cellSelect";
   pM.inputSelectorId=pM.participantField+"_Select";
   pM.textStudyId=pM.participantField+"_textStudy";

   pM.cellValueId=pM.participantField+"_cellValue";
   pM.inputValueId=pM.participantField+"_Value";
   pM.textLocalId=pM.participantField+"_textLocal";

   pM.inputManageLocalId=pM.participantField+"_ManageLocal";
   pM.inputManageStudyId=pM.participantField+"_ManageStudy";

   pM.mode="LOCAL";//or "STUDY"
   
   //dummy function to be overloaded by calling class
   pM.updateCrfEntry=function(){;}

   //init
   this.generateEntryField(pM);
   this.updateElements(pM);
   return pM;
}