
{% extends '@ajax-layout/layout.twig' %}

{% block body %}

<div id="code-gestion">
	<form class=" {% if post.valide_obligatoire == 1 %}formInvisible{% endif %}" id='form'>
		<input type="hidden" name="NUM_LOT" id="NUM_LOT" value="{{ post.NUM_LOT }}" />
		<input type="hidden" name="CODE_SI" id="CODE_SI" value="{{ post.CODE_SI }}" />
		<input type="hidden" name="CODE_STE" id="CODE_STE" value="{{ post.CODE_STE }}" />
		<input type="hidden" name="inputCG" id="inputCG" value="{{ post.inputCG }}" />
		<input type="hidden" name="affichageLibelle" id="affichageLibelle" value="{{ post.affichageLibelle }}" />
		<input type="hidden" name="CODE_GESTION_PAR_ID" id="CODE_GESTION_PAR_ID" value="{{ post.CODE_GESTION_PAR_ID }}" />
		<input type="hidden" name="IS_AUTHACHAT" id="IS_AUTHACHAT" value="{{ post.IS_AUTHACHAT }}" />
		{% if post.valide_obligatoire != 1 %}
		<div class="colonne last">
			<div class="row">
				{{ inputSwitch(
					'Uniquement les CG valides ?' | trad,
					'cg_valide',
					post.cg_valide | default('0'),
					attr({
						onchange: 'ajaxRechercheTableau('
							~ [
								path('Ajax.Treeview.codeGestion'),
								'code-gestion',
								'form'
							] |map(item => item |json) | join(',') 
							~')'
					}),
				) }}
			</div>
		</div>
		{% endif %}
		<div class="row single">
			{{ inputAdvance('TEXT', {
				titre: 'Recherche' | trad,
				name: 'search',
				value: post.search,
				inputAttr: {
					'data-onkeyup-echo': 'treeviewCgSearch(event.target.value)',
				}
			}) }}
		</div>
	</form>
	{% include '@Ajax/treeview/_treeview.twig' with {
		treeview: treeCG,
		name: 'ZoomCodeGest'
	} only %}
	<div class="modal-footer">
		<button class="button principal button_right" 
			onclick="choixCG()"
		>{{ 'Valider'|trad }}</button>
	</div>
	
<script>
window.mapCodeGest = {{ mapCodeGest | json }};
window.zoomCodeGestConfig = {
	cgParId: {{- CODE_GESTION_PAR_ID | json -}},
	affichagelibelle: {{- (post.affichageLibelle == '1') | json  -}},
	targetInput: {{ post.inputCG | json }},
};
	
function choixCG() {

	const codeGestSelected = document.querySelector('[name="ZoomCodeGest"]').value;
	const entity = mapCodeGest[ codeGestSelected ];
	const zoom = new InputZoom(
		document.querySelector('[name="'+CSS.escape(zoomCodeGestConfig.targetInput)+'"]')
	); 
	

	// TODO: move this code somewhere else
	// [Dossier n°34705]
	try {
		const tooltip = zoom.getFace()
			.closest('.white-tooltip')
			.querySelector('.sec-label-tooltip');
		if (tooltip && entity) {
			$(tooltip).text(entity.LIB_GES);
		}
	} catch(e) {
		// Ignore
	}

	if (entity == null) {
		zoom.set('', '');
	} else {
		zoom.set(
			// Si le paramétrage CODE_GESTION_PAR_ID == 1, la valeur à prendre est CODE_GES, sinon CODE_AFF
			zoomCodeGestConfig.cgParId ? entity.CODE_GES : entity.CODE_AFF,
			zoomCodeGestConfig.affichagelibelle
				? entity.LIB_GES+' ('+entity.CODE_AFF+')' 
				: entity.CODE_AFF,
			true // Safe ; value won't be validated
		);
	}
	desactivePopup();
}

//_____________________________________________________________________________
// Search

function treeviewCgshowItem(item) {
	item.style.display = '';

	// Show all parent item
	let current = item;
	while (current = current.parentElement.closest('[data-treeview-childwrapper]')) {
		// Assume previous sibling is a data-treeview-item
		current.previousElementSibling.style.display = '';
	}
}

function treeviewCgSearch(search) {
	const treeview = document.querySelector('[data-treeview="ZoomCodeGest"]');
	const listItem = treeview.querySelectorAll('[data-treeview-item]');

	// Case : search empty -> Show all item
	if (search.trim().length == 0) {
		for (const item of listItem) {
			item.style.display = '';
		}
		return;
	}

	// Hide all item
	for (const item of listItem) {
		item.style.display = 'none';
	}

	// Filter map with search
	const listEntity = Object.values(mapCodeGest).filter((entity) => {
		return fuzzyMatch(search, entity.CODE_GES)
			|| fuzzyMatch(search, entity.CODE_AFF)
			|| fuzzyMatch(search, entity.LIB_GES)
	});

	// Retrieve and show treeview-item
	for (const entity of listEntity) {
		treeviewCgshowItem(
			treeview.querySelector(
				'[data-treeview-item="' + CSS.escape(entity.CODE_GES) + '"]'
			)
		);
	}
}

function escapeRegExp(str) {
	return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function fuzzyMatch(pattern, str) {
	pattern = '.*' + pattern.split('').map(l => `${escapeRegExp(l)}.*`).join('');
	const re = new RegExp(pattern);
	return re.test(str);
}

</script>
</div>

{% endblock %}