// Global Variables
var jsonWorkorderList = { workorders: [] };
var jsonWorkorderList_ = { workorders: [] };
var jsonLaborList = { labors: [] };
var jsonStatusList = { status: [] };
var filtredWorkorders = { workorders: [] };
var craftList = { crafts: [] };

// Get the json aboject based on maximum int value for tag
function getLastObject(jsonArray, elementTagName) {
	const max = jsonArray.reduce(function (prev, current) {
		return (parseInt(prev[elementTagName]) > parseInt(current[elementTagName])) ? prev : current
	});
	return max;
}

// Get the json aboject based on exact int value for tag
function getObject(jsonArray, elementTagName, elementValue) {
	var max = jsonArray.find(function (obj) {
		return obj[elementTagName] === elementValue;
	});
	return max;
}
// Get Workorder by workorderid
function getWorkorderById(id) {
	return jsonWorkorderList.workorders.find(function (wo) {
		return wo.workorderID === parseInt(id);
	});
}
function getWorkordersById(idGroup, listework) {
	var liste = []
	jsonWorkorderList_.workorders.find(function (wo) {
		// console.log(wo.WOGROUP+' - '+typeof wo.WOGROUP+' / '+idGroup+' - '+ typeof idGroup)
		if (parseInt(wo.WOGROUP) === idGroup)
			liste.push(wo)
	});
	console.log(liste)
	return liste
}
// Get labor by laborcode
function getLaborByCode(code) {
	return jsonLaborList.labors.find(function (labor) {
		return labor.LABORCODE === code;
	});
}
// Get labors by orgid
function getLaborsByOrgid(org) {
	return jsonLaborList.labors.filter(function (labor) {
		return labor.ORGID === org;
	});
}
// Get labor by orgid and worksite
function getLaborsByOrgidWrkSite(org, wrksite) {
	return jsonLaborList.labors.find(function (labor) {
		return labor.ORGID === org && labor.ORGID.WORKSITE === wrksite;
	});
}
// Get event background color based on workorder systemstatus
function getColorByID(id) {
	// TODO get colors from parameters
	console.log("Given id " + id);
	console.log("WO count " + jsonWorkorderList.workorders.length)
	var systemStatus = jsonWorkorderList.workorders.find(wo => wo.workorderID === id).workorderSystemStatus;
	return getColorByStatus(systemStatus);
}

// Get application context path
function getBaseURL() {
	var path = window.location.pathname
	var idx = path.indexOf("/webclient");
	path = path.substring(0, idx);
	var port = window.location.port;
	var url = window.location.protocol + "//" + window.location.hostname;
	if (typeof port !== "undefined" && port !== "" && port !== null)
		url = url + ":" + window.location.port + path;
	else
		url = url + path;
	console.log("URL:" + url);
	return url
}

// Get Time from minutes
function getTimeFromMins(mins) {
	// do not include the first validation check if you want, for example,
	// getTimeFromMins(1530) to equal getTimeFromMins(90) (i.e. mins rollover)
	var h = mins / 60 | 0,
		m = mins % 60 | 0;
	return moment.utc().hours(h).minutes(m).format("HH:mm");
}

// Get minutes from float hours
function getMinsFromHours(hours) {

	return Math.floor(hours) * 60 + (hours - (Math.floor(hours))) * 60;
}
// get and init labor list
async function getLaborList() {
	let data = await fetchMaximoRequest('maximoSources/jsp/LABORS_DATA.jsp?talPlanifId=' + planifId);
	var div_employe = document.getElementById("liste_des_employes");
	var laborFilterOptions = document.getElementById('filtre_employe');
	//BCH affichage div employe pr test statut
	//console.log('liste emp : '+ div_employe);

	data.map(function (employe) {
		jsonLaborList.labors.push(employe);
		//BCH affich employe
		//console.log('employe:'+employe + '--liste +'+jsonLaborList.labors);
		var p_employe = document.createElement('p');
		p_employe.innerHTML = employe.LABORCODE + ' - ' + employe.DISPLAYNAME + '<br>' + employe.CALNUM + ' - ' + employe.SHIFTNUM + '<br>' + employe.CRAFT
		p_employe.id = employe.LABORID;
		p_employe.className = 'liste_employe';
		p_employe.draggable = true;
		// APPEND
		div_employe.appendChild(p_employe);
		var trait = document.createElement('hr');
		trait.className = 'trait_menu_employe';
		div_employe.appendChild(trait);
		
		var laborFilterOption = document.createElement('option');
		laborFilterOption.textContent = employe.LABORCODE + ' - ' + employe.DISPLAYNAME;
		laborFilterOption.setAttribute('value', employe.LABORCODE);
		laborFilterOptions.appendChild(laborFilterOption);
	});
}


//get status List
function getStatutList() {
	//let data = await fetchMaximoRequest('maximoSources/jsp/WORKORDERS_DATA.jsp?talPlanifId=' + planifId);
	var div_status = document.getElementById("liste_des_status");
	var statusFilterOptions = document.getElementById('filtre_statut');

	console.log('jsonWorkorderList.workorders.length : '+ jsonWorkorderList.workorders.length);
	for(var i = 0 ; i< jsonWorkorderList.workorders.length; i ++)
	{
		if (!jsonStatusList.status.includes(jsonWorkorderList.workorders[i].STATUS)) {
			jsonStatusList.status.push(jsonWorkorderList.workorders[i].STATUS);
			//console.log('liste des status : '+jsonStatusList.status);
			var p_status = document.createElement('p');
			//console.log('status test +'+status);
			p_status.innerHTML = jsonWorkorderList.workorders[i].STATUS;
			p_status.id = jsonWorkorderList.workorders[i].wonum;
			p_status.className = 'liste_statut';
			p_status.draggable = true;
			// APPEND
			//console.log('div status ' + div_status);
			div_status.appendChild(p_status);
			var trait = document.createElement('hr');
			trait.className = 'trait_menu_statut';
			div_status.appendChild(trait);
			//
			//console.log('status '+workorder.STATUS);

			//ligne commentée : insère des doubles dans la liste des status ; le même traitement des lignes d'après ?
			//optionsGenerator(workorder.STATUS,'filtre_statut')
			var statusFilterOption = document.createElement('option');
			statusFilterOption.textContent = jsonWorkorderList.workorders[i].STATUS;
			statusFilterOption.setAttribute('value', jsonWorkorderList.workorders[i].STATUS);
			statusFilterOptions.appendChild(statusFilterOption);
		}

	}
	/* data.map(function (workorder) {

		//test d'existence dans tableau pour enlever les doublons dans la liste
		if (!jsonStatusList.status.includes(workorder.STATUS)) {
			jsonStatusList.status.push(workorder.STATUS);
			//console.log('liste des status : '+jsonStatusList.status);
			var p_status = document.createElement('p');
			//console.log('status test +'+status);
			p_status.innerHTML = workorder.STATUS;
			p_status.id = workorder.wonum;
			p_status.className = 'liste_statut';
			p_status.draggable = true;
			// APPEND
			//console.log('div status ' + div_status);
			div_status.appendChild(p_status);
			var trait = document.createElement('hr');
			trait.className = 'trait_menu_statut';
			div_status.appendChild(trait);
			//
			//console.log('status '+workorder.STATUS);

			//ligne commentée : insère des doubles dans la liste des status ; le même traitement des lignes d'après ?
			//optionsGenerator(workorder.STATUS,'filtre_statut')
			var statusFilterOption = document.createElement('option');
			statusFilterOption.textContent = workorder.STATUS;
			statusFilterOption.setAttribute('value', workorder.STATUS);
			statusFilterOptions.appendChild(statusFilterOption);
		}
	}); */
}

//get and init gamme list
/*async function getGammeList(){
	let data = await fetchMaximoRequest('maximoSources/jsp/WORKORDERS_DATA.jsp?talPlanifId='+planifId);
	var div_gamme = document.getElementById("liste_des_gammes")
	var gammeFilterOptions = document.getElementById('filtre_gamme');
	data.map(function(gamme){
		jsonGammeList.gammes.push(gamme);
		var p_gamme = document.createElement('p');
		p_gamme.innerHTML=gamme.JPNUM;
		p_gamme.id=gamme.JPNUM;
		p_gamme.className='liste_gamme';
		p_gamme.draggable=true;
		//APPEND
		div_gamme.appendChild(p_gamme);
		var trait = document.createElement('hr');
		trait.classname='trait_menu_gamme';
		div
		
	});
}*/


//BCH fct filtrer la liste des intervetions
function filterWorkorders() {
	getWorkorderList();
	printWorkorders();
}


//fonction get Craft list from assignments
function setCraftList()
{
	var filteredCrafts = { crafts: [] };
	for(var i = 0 ; i < craftList.crafts.length; i++)
	{
			if (!filteredCrafts.crafts.includes(craftList.crafts[i].CRAFT) && craftList.crafts[i].CRAFT != '') {
				filteredCrafts.crafts.push(craftList.crafts[i].CRAFT);
				optionsGenerator(craftList.crafts[i].CRAFT, 'filtre_corp_metier');
			}
	}
	//craftList = filteredCrafts;
	
	
} 

//BCH fct afficher interventions dans section inervention
function printWorkorders() {
	// clear div list interventions
	$("#liste_des_interventions").html("");
	var div_intervention = document.getElementById("liste_des_interventions");
	if (typeof (filtredWorkorders) !== 'undefined' && filtredWorkorders.workorders.length > 0) {
		for (var i = 0; i < filtredWorkorders.workorders.length; i++) {
			console.log('filtredWorkorders.workorders.statut' + filtredWorkorders.workorders[i].STATUS);
			var p_intervention = document.createElement('p');
			p_intervention.innerHTML = '<strong>' + filtredWorkorders.workorders[i].WONUM + ': ' + '</strong>' + filtredWorkorders.workorders[i].workorderDescription + '<br>';
			if (typeof filtredWorkorders.workorders[i].assetNum !== "undefined") {
				p_intervention.innerHTML += '<strong>' + filtredWorkorders.workorders[i].assetNum + ': ' + '</strong>' + filtredWorkorders.workorders[i].assetDescription + '<br>';
			}
			else {
				if (typeof filtredWorkorders.workorders[i].woLocation !== "undefined") {
					p_intervention.innerHTML += '<strong>' + filtredWorkorders.workorders[i].woLocation + ': ' + '</strong>' + filtredWorkorders.workorders[i].woLocationDescription + '<br>';
				}
			}
			if (typeof filtredWorkorders.workorders[i].woTargStartDate !== "undefined") {
				p_intervention.innerHTML += '<strong>' + 'Début objectif: ' + '</strong>' + filtredWorkorders.workorders[i].woTargStartDate + '<br>';
			}
			p_intervention.innerHTML += '<strong>' + 'Statut: ' + '</strong>' + filtredWorkorders.workorders[i].workorderStatus;
			p_intervention.id = filtredWorkorders.workorders[i].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);
		}
		filtredWorkorders.workorders = [];
	}
	else {
		//console.log(' dans jsonWorkorderList.workorders ');
		if (statusFiltredList.length !== 0 || gammeFilteredList.length > 0 || emplacementFiltredList.length > 0 || actifFiltredList.length > 0 || pkdebutFiltredList.length > 0 || pkfinFiltredList.length > 0 || corpmetierFiltredList.length > 0)
		console.log('Do nothing');
		else{
		jsonWorkorderList.workorders.forEach(loopWokorders);
		function loopWokorders(workorder) {
			var p_intervention = document.createElement('p');
			p_intervention.innerHTML = '<strong>' + workorder.WONUM + ': ' + '</strong>' + workorder.workorderDescription + '<br>';
			if (typeof workorder.assetNum !== "undefined") {
				p_intervention.innerHTML += '<strong>' + workorder.assetNum + ': ' + '</strong>' + workorder.assetDescription + '<br>';
			}
			else {
				if (typeof workorder.woLocation !== "undefined") {
					p_intervention.innerHTML += '<strong>' + workorder.woLocation + ': ' + '</strong>' + workorder.woLocationDescription + '<br>';
				}
			}
			if (typeof workorder.woTargStartDate !== "undefined") {
				p_intervention.innerHTML += '<strong>' + 'Début objectif: ' + '</strong>' + workorder.woTargStartDate + '<br>';
			}
			p_intervention.innerHTML += '<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);
		}}
	}
}


// get and init workorder list
async function getWorkorderList() {
	if (statusFiltredList.length !== 0) {
		if (filtredWorkorders.length > 0) {
			var tempWorkorders = { workorders: [] };
			for (j = 0; j < statusFiltredList.length; j++) {

				var i = 0;
				while (i < filtredWorkorders.workorders.length) {
					if (filtredWorkorders.workorders[i].STATUS === statusFiltredList[j]) {
						tempWorkorders.workorders.push(filtredWorkorders.workorders[i]);
					}
					i++;
				}
			}
			filtredWorkorders = tempWorkorders;
		}
		else {
			for (var j = 0; j < statusFiltredList.length; j++) {
				var i = 0;
				while (i < jsonWorkorderList.workorders.length) {
					if (jsonWorkorderList.workorders[i].STATUS === statusFiltredList[j]) {
						filtredWorkorders.workorders.push(jsonWorkorderList.workorders[i]);
					}
					i++;
				}
			}
		}

	}
	if (gammeFilteredList.length > 0) {
		if (filtredWorkorders.workorders.length > 0) {
			var tempWorkorders = { workorders: [] };
			for (j = 0; j < gammeFilteredList.length; j++) {
				var i = 0;
				while (i < filtredWorkorders.workorders.length) {
					if (filtredWorkorders.workorders[i].JPNUM === gammeFilteredList[j]) {
						tempWorkorders.workorders.push(filtredWorkorders.workorders[i]);
					}
					i++;
				}
			}
			filtredWorkorders = tempWorkorders;
		}
		else {
			for (j = 0; j < gammeFilteredList.length; j++) {

				var i = 0;
				while (i < jsonWorkorderList.workorders.length) {
					if (jsonWorkorderList.workorders[i].JPNUM === gammeFilteredList[j]) {
						filtredWorkorders.workorders.push(jsonWorkorderList.workorders[i]);
					}
					i++;
				}
			}
		}
	}
	if (emplacementFiltredList.length > 0) {
		if (filtredWorkorders.workorders.length > 0) {
			var tempWorkorders = { workorders: [] };
			for (j = 0; j < emplacementFiltredList.length; j++) {
				var i = 0;
				while (i < filtredWorkorders.workorders.length) {
					if (filtredWorkorders.workorders[i].LOCATION === emplacementFiltredList[j]) {
						tempWorkorders.workorders.push(filtredWorkorders.workorders[i]);
					}
					i++;
				}
			}
			filtredWorkorders = tempWorkorders;
		}
		else {
			for (j = 0; j < emplacementFiltredList.length; j++) {
				var i = 0;
				while (i < jsonWorkorderList.workorders.length) {
					if (jsonWorkorderList.workorders[i].LOCATION === emplacementFiltredList[j]) {
						filtredWorkorders.workorders.push(jsonWorkorderList.workorders[i]);
					}
					i++;
				}
			}
		}

	}
	if (actifFiltredList.length > 0) {
		//console.log('actifFiltredList.length' + actifFiltredList.length);
		if (filtredWorkorders.workorders.length > 0) {
			var tempWorkorders = { workorders: [] };
			for (j = 0; j < actifFiltredList.length; j++) {
				var i = 0;
				while (i < filtredWorkorders.workorders.length) {
					if (filtredWorkorders.workorders[i].ASSETNUM === actifFiltredList[j]) {
						tempWorkorders.workorders.push(filtredWorkorders.workorders[i]);
					}
					i++;
				}
			}
			filtredWorkorders = tempWorkorders;
		}
		else {
			console.log('actifFiltredList.length' + actifFiltredList.length);
			for (j = 0; j < actifFiltredList.length; j++) {
				var i = 0;
				while (i < jsonWorkorderList.workorders.length) {
					//console.log('jsonWorkorderList.workorders[i].ASSETNUM : '+ jsonWorkorderList.workorders[i].ASSETNUM);
					if (jsonWorkorderList.workorders[i].ASSETNUM === actifFiltredList[j]) {
						filtredWorkorders.workorders.push(jsonWorkorderList.workorders[i]);
					}
					i++;
				}
			}
		}
	}
	if (pkdebutFiltredList.length > 0) {
		//console.log('actifFiltredList.length' + actifFiltredList.length);
		if (filtredWorkorders.workorders.length > 0) {
			var tempWorkorders = { workorders: [] };
			for (j = 0; j < pkdebutFiltredList.length; j++) {
				var i = 0;
				while (i < filtredWorkorders.workorders.length) {
					if (filtredWorkorders.workorders[i].WOEQ5 === pkdebutFiltredList[j]) {
						tempWorkorders.workorders.push(filtredWorkorders.workorders[i]);
					}
					i++;
				}
			}
			filtredWorkorders = tempWorkorders;
		}
		else {
			console.log('actifFiltredList.length' + pkdebutFiltredList.length);
			for (j = 0; j < pkdebutFiltredList.length; j++) {
				var i = 0;
				while (i < jsonWorkorderList.workorders.length) {
					//console.log('jsonWorkorderList.workorders[i].ASSETNUM : '+ jsonWorkorderList.workorders[i].ASSETNUM);
					if (jsonWorkorderList.workorders[i].WOEQ5 === pkdebutFiltredList[j]) {
						filtredWorkorders.workorders.push(jsonWorkorderList.workorders[i]);
					}
					i++;
				}
			}
		}
	}
	if (pkfinFiltredList.length > 0) {
		//console.log('actifFiltredList.length' + actifFiltredList.length);
		if (filtredWorkorders.workorders.length > 0) {
			var tempWorkorders = { workorders: [] };
			for (j = 0; j < pkdebutFiltredList.length; j++) {
				var i = 0;
				while (i < filtredWorkorders.workorders.length) {
					if (filtredWorkorders.workorders[i].WOEQ7 === pkfinFiltredList[j]) {
						tempWorkorders.workorders.push(filtredWorkorders.workorders[i]);
					}
					i++;
				}
			}
			filtredWorkorders = tempWorkorders;
		}
		else {
			console.log('actifFiltredList.length' + pkfinFiltredList.length);
			for (j = 0; j < pkfinFiltredList.length; j++) {
				var i = 0;
				while (i < jsonWorkorderList.workorders.length) {
					//console.log('jsonWorkorderList.workorders[i].ASSETNUM : '+ jsonWorkorderList.workorders[i].ASSETNUM);
					if (jsonWorkorderList.workorders[i].WOEQ7 === pkfinFiltredList[j]) {
						filtredWorkorders.workorders.push(jsonWorkorderList.workorders[i]);
					}
					i++;
				}
			}
		}
	}



	for(var j = 0; j <corpmetierFiltredList.length; j++ )
	console.log('filtered crafts CRAFT : ' + corpmetierFiltredList[j] + ' and wonum  récupéré avec la concordance clé valeur : ' + craftList.crafts.find(craft => craft.CRAFT === corpmetierFiltredList[j] ).WONUM );
	//filter interventions by craft list
	if (corpmetierFiltredList.length > 0) {
		//console.log('actifFiltredList.length' + actifFiltredList.length);
		if (filtredWorkorders.workorders.length > 0) {
			var tempWorkorders = { workorders: [] };
			for (j = 0; j < corpmetierFiltredList.length; j++) {
				var i = 0;
				while (i < filtredWorkorders.workorders.length) {
					if (filtredWorkorders.workorders[i].WONUM === craftList.crafts.find(craft => craft.CRAFT === corpmetierFiltredList[j] ).WONUM ) {
						tempWorkorders.workorders.push(filtredWorkorders.workorders[i]);
					}
					i++;
				}
			}
			filtredWorkorders = tempWorkorders;
		}
		else {
			console.log('actifFiltredList.length' + craftList.crafts.length);
			for (j = 0; j < corpmetierFiltredList.length; j++) {
				var i = 0;
				while (i < jsonWorkorderList.workorders.length) {
					//console.log('jsonWorkorderList.workorders[i].ASSETNUM : '+ jsonWorkorderList.workorders[i].ASSETNUM);
					if (jsonWorkorderList.workorders[i].WONUM === craftList.crafts.find(craft => craft.CRAFT === corpmetierFiltredList[j] ).WONUM ) {
						filtredWorkorders.workorders.push(jsonWorkorderList.workorders[i]);
					}
					i++;
				}
			}
		}
	} 
}

//afficher les interventions à l'initialisation, s'execute qu'une seule fois
// get and init workorder list
async function initWorkorderList() {

	//test de récupration de la date du calendrier pour l'impression PDF
	console.log('date : ' + document.getElementById('calendar').firstChild.firstChild.textContent);



	let data = await fetchMaximoRequest('maximoSources/jsp/WORKORDERS_DATA.jsp?talPlanifId=' + planifId);
	var div_intervention = document.getElementById("liste_des_interventions");
	data.map(function (workorder) {
		// Add the workorder object to the list
		jsonWorkorderList.workorders.push(workorder);
		var p_intervention = document.createElement('p');
		p_intervention.innerHTML = '<strong>' + workorder.WONUM + ': ' + '</strong>' + workorder.workorderDescription + '<br>';
		if (typeof workorder.assetNum !== "undefined") {
			p_intervention.innerHTML += '<strong>' + workorder.assetNum + ': ' + '</strong>' + workorder.assetDescription + '<br>';
		}
		else {
			if (typeof workorder.woLocation !== "undefined") {
				p_intervention.innerHTML += '<strong>' + workorder.woLocation + ': ' + '</strong>' + workorder.woLocationDescription + '<br>';
			}
		}
		if (typeof workorder.woTargStartDate !== "undefined") {
			p_intervention.innerHTML += '<strong>' + 'Début objectif: ' + '</strong>' + workorder.woTargStartDate + '<br>';
		}
		p_intervention.innerHTML += '<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);
	});

	let craftData = await fetchMaximoRequest('maximoSources/jsp/CRAFT_DATA.jsp?talPlanifId=' + planifId);
	craftData.map(function(assignment)
	{	
		craftList.crafts.push(assignment);	
	});
	getStatutList();
	setCraftList();
}
// get businesshours
async function getBusinessHours(cal) {
	let data = await fetchMaximoRequest('maximoSources/jsp/businessHours.jsp?talPlanifId=' + planifId);
	var businessHours = {
		startTime: data.startTime,
		endTime: data.endTime,
		daysOfWeek: data.daysOFWeek
	};
	cal.setOption('businessHours', businessHours);
}
function getWorkorderAttributeValue(workorderID, attributeName) {
	var workorderElement = $('#' + workorderID).data(attributeName);
}

function getColorByStatus(systemStatus) {
	// TODO get colors from parameters
	const liste_1 = ['APPR', 'INPRG'];
	const liste_2 = ['CAN', 'CLOSE', 'COMP'];
	const liste_3 = ['HISTEDIT', 'WAPPR', 'WMATL', 'WSCH'];
	if (liste_1.includes(systemStatus)) return '#0FC4A8'
	else
		if (liste_2.includes(systemStatus)) return '#00B1F7'
		else
			if (liste_3.includes(systemStatus)) return '#0F9DC4'
			else
				return '#21e6d7'

}