// To make Object.entries() support older environments
if (!Object.entries) {
	// from : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#polyfill
	Object.entries = (obj) => {
		let ownProps = Object.keys(obj),
			i = ownProps.length,
			resArray = new Array(i); // preallocate the Array
		while (i--) resArray[i] = [ownProps[i], obj[ownProps[i]]];

		return resArray;
	};
}

$(document).ready(() => {
	console.log("[FORM] load_data.js"); // DEBUG
	window.data_ticket_form.forEach((item) => {
		let { choices, name } = item;

		if (name === "ticket_type") choices = ["Anomalie", "Évolution"];

		let select_tags = $(`select#${name}:not('.static')`);

		let select_tag = select_tags.length == 1 ? select_tags[0] : null;
		// test if the <select> tag with a specific id exists and is no static
		if (select_tag) {
			// test if it is a array
			if (Array.isArray(choices)) {
				choices.forEach((choice) =>
					select_tag.append(new Option(choice, choice))
				);
			} else {
				//otherwise we transform into an associative array
				Object.entries(choices).forEach(function ([key, value]) {
					select_tag.append(new Option(key, value));
				});
			}
		} else {
			// console.log("No select for id " + name); // DEBUG
		}
		// set default value to "medium" for priority field
		$("#priority").val("2");
		// hide the subbox fields which depend on the selected type of ticket
		$(".subbox input, .subbox select").prop("disabled", true);
	});
});

const jsConnector = {
	/**
	 * load "value" in the field which has for id "name"
	 * @param {*} name field id
	 * @param {*} value field value
	 */
	loadPrefilledField: function (name, value) {
		let select_tags = $(`#${name}`);
		let select_tag = select_tags.length == 1 ? select_tags[0] : null;
		if (select_tag) {
			select_tags.val(`${value}`);
			console.log(`${name} field has been filled`);
		} else {
			console.log("No field for id " + name + " to fill");
		}
	},
};

function getJsConnector() {
	return jsConnector;
}
