// Init assignement details dialog
function initAssignmentDetails(eventInfo, action){
    var eventObject = eventInfo.event;
    var colorModal = getColorByStatus(eventObject.extendedProps.workorderSystemStatus)
    intiColor(colorModal)
    showLessInfosModal()  
    var assignmentStartDate = document.getElementById('assignmentStartDate');
    var assignmentStartTime = document.getElementById('assignmentStartTime');
    var assignmentDuration = document.getElementById('assignmentDuration');
	var laborList = document.getElementById('laborList');
    var saveAssignmentBtn = document.getElementById('saveAssignmentBtn');
    var cancelBtn = document.getElementById('cancelBtn');
    var laborListDialog = document.getElementById('laborList');
    var assignmentWo = document.getElementById('assignmentWo')
    var assignmentWoDescr = document.getElementById('assignmentWoDescr')
    var assignmentWoParent= document.getElementById('assignmentWoParent')
    var assignmentWoParentDescr= document.getElementById('assignmentWoParentDescr')
    var assignmentPlan = document.getElementById('assignmentPlan')
    var assignmentPlanDescr = document.getElementById('assignmentPlanDescr')
    var assignmentMP = document.getElementById('assignmentMP')
    var assignmentMPDescr = document.getElementById('assignmentMPDescr')
    var assignmentType = document.getElementById('assignmentType')
    var assignmentTypeDescr = document.getElementById('assignmentTypeDescr')
    var assignmentStatut= document.getElementById('assignmentStatut')
    var assignmentStatutDescr= document.getElementById('assignmentStatutDescr')
    var assignmentWoPriorty= document.getElementById('assignmentWoPriorty')
    var assignmentActif = document.getElementById('assignmentActif')
    var assignmentActifDescr = document.getElementById('assignmentActifDescr')
    var assignmentLocation = document.getElementById('assignmentLocation')
    var assignmentLocationDescr = document.getElementById('assignmentLocationDescr')
    var assignmentSite = document.getElementById('assignmentSite')
    var assignmentSiteDescr = document.getElementById('assignmentSiteDescr')
    var assignmentDO = document.getElementById('assignmentDO')
    var assignmentFO= document.getElementById('assignmentFO')
    var assignmentDP = document.getElementById('assignmentDP')
    var assignmentFP=document.getElementById('assignmentFP')
    var assignmentDA = document.getElementById('assignmentDA')
    var assignmentFA = document.getElementById('assignmentFA')
	// get event extended data
	var nsfields = eventObject.extendedProps;
    // get workorder object
    var wo = getWorkorderById(nsfields.workorderID);
    assignmentWo.value=wo.WONUM;
    assignmentWoDescr.value=wo.workorderDescription
    assignmentStatut.value= wo.workorderStatus;
    assignmentStatutDescr.value= wo.woStatusDescription
    assignmentSite.value=wo.siteID;
    assignmentSiteDescr.value=wo.siteDescription;
    if(wo.woParent !== undefined) {
        assignmentWoParent.value = wo.woParent;
        assignmentWoParentDescr.value = wo.woParentDescription;
    }
    else 
    {
        assignmentWoParent.value = '';
        assignmentWoParentDescr.value = '';
    }
    if( wo.woJobPlan !== undefined) {
        assignmentPlan.value= wo.woJobPlan;
        assignmentPlanDescr.value= wo.woJobPlanDescription;
    }
    else
    {
        assignmentPlan.value= '';
        assignmentPlanDescr.value= '';
    }
    if(wo.woPm !== undefined) {
        assignmentMP.value= wo.woPm;
        assignmentMPDescr.value= wo.woPmDescription;
    }
    else
    {
        assignmentMP.value= '';
        assignmentMPDescr.value= '';
    }
    if(wo.woWorkType !== undefined) {
        assignmentType.value=wo.woWorkType;
        assignmentTypeDescr.value=wo.woWorkTypeDescription;
    }
    else
    {
        assignmentType.value='';
        assignmentTypeDescr.value='';
    }
    if(wo.workorderPriority !== undefined) {
        assignmentWoPriorty.value =wo.workorderPriority
    }
    else
    {
        assignmentWoPriorty.value =''
    }
    if(wo.assetNum !== undefined) {
        assignmentActif.value=wo.assetNum;
        assignmentActifDescr.value=wo.assetDescription;
    }
    else
    {
        assignmentActif.value='';
        assignmentActifDescr.value='';
    }
    if(wo.woLocation !== undefined) {
        assignmentLocation.value=wo.woLocation;
        assignmentLocationDescr.value=wo.woLocationDescription;
    }
    else
    {
        assignmentLocation.value='';
        assignmentLocationDescr.value='';
    }

    if(wo.woTargStartDate !== undefined)
        assignmentDO.value=moment(wo.woTargStartDate,"dd/MM/yyyy HH:mm").format('DD/MM/YYYY HH:mm')
    else
        assignmentDO.value=''

    if(wo.woTargCompDate !== undefined)    
        assignmentFO.value=moment(wo.woTargCompDate,"dd/MM/yyyy HH:mm").format('DD/MM/YYYY HH:mm')
    else
        assignmentFO.value=''

    if(wo.woSchedStart !== undefined)
        assignmentDP.value=moment(wo.woSchedStart,"dd/MM/yyyy HH:mm").format('DD/MM/YYYY HH:mm')
    else
        assignmentDP.value=''

    if(wo.woSchedFinish !== undefined)
        assignmentFP.value=moment(wo.woSchedFinish,"dd/MM/yyyy HH:mm").format('DD/MM/YYYY HH:mm')
    else
        assignmentFP.value=''

    if(wo.woSNEConstraint !== undefined)
        assignmentDA.value=moment(wo.woSNEConstraint,"dd/MM/yyyy HH:mm").format('DD/MM/YYYY HH:mm')
    else
        assignmentDA.value=''

    if(wo.woFNLConstraint !== undefined)
        assignmentFA.value=moment(wo.woFNLConstraint,"dd/MM/yyyy HH:mm").format('DD/MM/YYYY HH:mm')
    else
        assignmentFA.value=''

    // Clear the labor list
    while (laborListDialog.firstChild) {
        laborListDialog.removeChild(laborListDialog.lastChild);
      }
      if(action=='NEWAFFECT')

    // Add existing labor to the labor list if not existing
    if (typeof nsfields.laborCode !== "undefined" && nsfields.laborCode !== null) {
        
           let highlightedCurrentLabor = getLaborByCode(nsfields.laborCode);
            if (typeof highlightedCurrentLabor === "undefined"){
                var option_employe = document.createElement('option');
                option_employe.textContent=nsfields.laborCode +' - '+ nsfields.displayName;
                option_employe.setAttribute('value',nsfields.laborCode);
                laborListDialog.appendChild(option_employe);
            }
        }
    
    // Populate labor list based on orgid
    let highlightedLaborList = getLaborsByOrgid(wo.orgID);
    highlightedLaborList.forEach(function(laborItem) {
        var option_employe = document.createElement('option');
	    option_employe.textContent=laborItem.LABORCODE +' - '+ laborItem.DISPLAYNAME;
	    option_employe.setAttribute('value',laborItem.LABORCODE);
	    laborListDialog.appendChild(option_employe);
      });
    // TODO: Add filter labor by worksite (Based on parameter)
    if(action=='NEWAFFECT')
    laborList.value=''
    else
    laborList.value=nsfields.laborCode;
	// Init dialog data from event data
	var momentStart = moment(eventObject.start);
    //dialogTitle.textContent="Détail affectation";
    assignmentDuration.value= getTimeFromMins(getMinsFromHours(nsfields.laborHours));    
    assignmentStartTime.value = momentStart.format("HH:mm");	
    assignmentStartDate.value = momentStart.format("DD/MM/YYYY");
    // Add action click to saveAssignment
    saveAssignmentBtn.onclick= function(){
		// Get data from dialog
        var laborCodeValue = document.getElementById('laborList').value
        var assignmentStartDateValue = assignmentStartDate.value
        var assignmentStartTimeValue = assignmentStartTime.value
        var assignementDurationValue= assignmentDuration.value

		// Prepare data for functions
        var scheduleDate = moment(assignmentStartDateValue+" "+assignmentStartTimeValue,"DD/MM/YYYY HH:mm").format("YYYY-MM-DDTHH:mm:ss");
        var hours = moment.duration(assignementDurationValue).asHours();
        let assingmentId_ 
        if(action=='DUPLICATE' || action=='NEWAFFECT')
        {assingmentId_ = ''}
        else 
        {
         assingmentId_ = parseInt(nsfields.assingmentId)
      }
		// Call saveAssignment
        saveAssignment(eventObject,nsfields.workorderID,nsfields.WONUM,assingmentId_,laborCodeValue,scheduleDate,hours);
        
        wo.woAssignedAssignments = wo.woAssignedAssignments + 1;
        wo.woTotalAssignments = wo.woTotalAssignments + 1;
        // TODO: Possibility to choose between existing non assigned assignments
        if(action!='DUPLICATE' && action!='NEWAFFECT' && eventInfo.draggedEl != undefined)
            eventInfo.draggedEl.parentNode.removeChild(eventInfo.draggedEl);
        $("#assignmentDetails").modal('hide');  
    }

    // Add action click to cancel modification and remove the droped event
    cancelBtn.onclick= function(){
        if (nsfields.assingmentId == null || nsfields.assingmentId==="")
            eventObject.remove();
    }
    }
 // Save Assignement
    function saveAssignment(eventObject,workorderID,wonum,assingmentId,employe,startDateTime,laborhrs,action_) {
        if(action_=='DUPLICATE' || action_=='NEWAFFECT')
        {assingmentId = ''}
        console.log(action_ + assingmentId)
        var laborCode = employe
        if (typeof laborCode === "undefined" || laborCode === null)
            laborCode = ''
        var request = new XMLHttpRequest();
        let params = 'ASSIGNMENT.id1.ASSIGNMENTID='+(isNaN(assingmentId) ? '' : assingmentId) +'&ASSIGNMENT.id1.LABORHRS='+
        laborhrs.toString().replace(/\./g, ',')+'&ASSIGNMENT.id1.LABORCODE='+laborCode+'&ASSIGNMENT.id1.scheduledate='+startDateTime+'&_compact=true&_format=json'; //.replace(".",",") .replace(/\./g, ',')
        var url =getBaseURL()+'/rest/os/PLANIF_ASSIGN/'+ workorderID;
        request.onreadystatechange = state_change_;
        request.open("POST",url, true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.send(params);
        console.log(url+params);
        function state_change_() {
          if (request.readyState == 4) { // 4 = "loaded"
            if (request.status == 200  || request.status == 204 ) { // 200 = OK
                if(typeof eventObject.id !== "undefined" || eventObject.id !== null || eventObject.id===""){
                    eventObject._calendar.refetchEvents();
                    eventObject.remove();
                }
                else {     
                    // Use this once the bug with event id is fixed           
                    var root = JSON.parse(request.responseText);
                    var assignmentObject = root['PLANIF_ASSIGNSet']['WORKORDER']['ASSIGNMENT'];
				    var assignmentResult=getObject(assignmentObject,'assignmentid',eventObject.id);
                    // update eventObject
                    var endDateTime = moment.utc(startDateTime).add(getMinsFromHours(laborhrs),'minutes').format("YYYY-MM-DDTHH:mm:ss");
                    eventObject.setDates(startDateTime,endDateTime,false);
                    eventObject.setExtendedProp("assingmentId",assignmentResult['assignmentid']);
                    eventObject.setExtendedProp("assingmentStatus",assignmentResult['status']);
		            eventObject.setExtendedProp("laborHours",assignmentResult['laborhrs']);
		            eventObject.setExtendedProp("laborCode",assignmentResult['laborcode']);
		            eventObject.setExtendedProp("displayName",assignmentResult['labor']['person']['displayname']);
		            eventObject.setExtendedProp("taskID",assignmentResult['spi:taskid']);
                    eventObject.setExtendedProp("craft",assignmentResult['spi:craft']);
                    eventObject.setExtendedProp("woTargCompDate",assignmentResult['spi:targcompdate']);
                    eventObject.setExtendedProp("woFNLConstraint",assignmentResult['spi:fnlconstraint']);
                }
            }
            else {
                alert(request.status + " - " + request.statusText);
            }
        }
    }
}
// DELETE AFFECTAITON 
function deleteAssignment (eventObject, assingmentId){
	var request = new XMLHttpRequest();
	var url=getBaseURL()+'/rest/mbo/assignment/'+ assingmentId
	request.onreadystatechange= state_change_delete
	request.open("DELETE",url,true)
	request.send()
	function  state_change_delete() {
		// 4 = "loaded"
		  if (request.status == 200  || request.status == 204 )  // 200 = OK
				  eventObject.remove();
			  else     	
			  console.log('Erreur de suppression / '+request.status + " - " + request.statusText);
		 
	  }
	// get event extended data
	var nsfields = eventObject.extendedProps;
    
    // get workorder object
	var workorder = getWorkorderById(nsfields.workorderID);
	workorder.woAssignedAssignments = workorder.woAssignedAssignments - 1;
	workorder.woTotalAssignments = workorder.woTotalAssignments - 1;
	// TODO: Update non assigned assignments when implemented
	if (workorder.woAssignedAssignments===0)
	{
		var div_intervention = document.getElementById ("liste_des_interventions");
		var p_intervention = document.createElement('p');
		p_intervention.innerHTML='<strong>'+workorder.WONUM+': '+'</strong>'+workorder.workorderDescription+'<br>';
		if (typeof workorder.woTargStartDate !== undefined) {
			p_intervention.innerHTML +='<strong>'+'Début objectif: '+'</strong>'+workorder.woTargStartDate;
		}
		p_intervention.innerHTML += '<br> <strong>'+'Statut: '+'</strong>'+workorder.workorderStatus;
	
		p_intervention.id=workorder.workorderID;
	
		p_intervention.className='liste_intervention';
		p_intervention.draggable=true;
		// APPEND
		var trait = document.createElement('hr');
		trait.className='trait_menu_intervention';
        p_intervention.appendChild(trait);
        div_intervention.appendChild(p_intervention);
  }
 }
//
function showLessInfosModal()
{
    if (!navigator.userAgent.includes('Chrome')) 
    $('.last_hr_line').css('margin-top','35px')
    else
    $('.last_hr_line').css('margin-top','0px')
    document.getElementById('modal-title').style.paddingLeft='20%'
    $('#modal-footer').css('display','inline')
    $('.vertical-line').css('display','none')
    $('.hr_line').css('display','none')
    $('#modalInterInfo').css('display','none')
    $('#modalTypeInfo').css('display','none')
    $('#modalActifInfo').css('display','none')
    $('#modalDivAff').css('width','80%') //447px
    $('#modalDivAff').css('margin-left','10%') // 0
    $('#modalSiteInfo').css('display','none')
    $('#modalDatesInfo').css('display','none')
    $('#cellInfosBtn').css('display','none')
    $('#cellValiderBtn').css('text-align','center')
    $("#footerTableMini").removeClass("footerDisplay");
    $('.modal-content').css('width','402px') //1150px // 520px
    $('.modal-body').css('height','330px') //500px
    $('.modal-dialog').css('left','20%') // 0px // 15%
    $('#headCloseBtn').css('right','50px') //60px
}
function showMoreInfosModal()
{
    document.getElementById('modal-title').style.paddingLeft='0'
    $('.last_hr_line').css('margin-top','15px')
    $('#modal-footer').css('display','inline-block')
    $('.modal-content').css('width','1150px') //1150px
    $('#modalDivAff').css('width','447px') //447px
    $('.vertical-line').css('display','inline-block')
    $('.hr_line').css('display','block')
    $('#modalInterInfo').css('display','block')
    $('#modalTypeInfo').css('display','block')
    $('#modalActifInfo').css('display','inline-block')
    $('#modalDivAff').css('margin-left','0') // 0
    $('#modalDivAff').css('display','inline-block') 
    $('#modalSiteInfo').css('display','block')
    $('#modalDatesInfo').css('display','block')
    $('#cellInfosBtn').css('display','block')
    $('#cellValiderBtn').css('text-align','right')
    $("#footerTableMini").addClass("footerDisplay");
    $('.modal-body').css('height','500px') //500px
    $('.modal-dialog').css('left','0') // 0px
    $('#headCloseBtn').css('right','20px')
    
}

function intiColor(colorModal)
{
    document.getElementById('modal-header').style.backgroundColor=colorModal
    $('.infos').css('background-color',colorModal)
    $("<style type='text/css'> .infos:hover{ background-color: white !important; color:"+colorModal+" ; border: 1px solid "+colorModal+";} </style>").appendTo("head");
}