/**
 * Conditions
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const conditionPlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {
	form.querySelectorAll('.dp-condition').forEach((targetElement) => {
	    const conditionConfig = JSON.parse(targetElement.dataset.condition);

	    // bind to target
	    // TODO: might not work on some fields because of hidden fields.
	    document.querySelectorAll('.' + conditionConfig.condition + ' :where(input,select,textarea)').forEach((sourceElement, i) => {
		sourceElement.addEventListener("change", () => {this.checkCondition(targetElement);});
		this.checkCondition(targetElement);
	    });
	});
    },
    checkCondition: function(targetElement) {
	const conditionConfig = JSON.parse(targetElement.dataset.condition);
	document.querySelectorAll('.' + conditionConfig.condition + ' :where(input,select,textarea)').forEach((sourceElement, i) => {
	    var sourceValue = sourceElement.value;
	    if (sourceElement.getAttribute('type') == 'checkbox' || sourceElement.getAttribute('type') == 'radio') {
		sourceValue = sourceElement.querySelector(':checked')?.value ?? null;
	    }
	    if (sourceElement.tagName == 'select') {
		//const select =sourceElement.querySelector('select');
		// sourceValue = select.options[select.selectedIndex];
		sourceValue = sourceElement.querySelector('option:selected')?.value ?? null;
	    }

	    var showTarget = false;
	    if (conditionConfig.values.length === 0) {
		showTarget = sourceValue !== '';
	    } else {
		showTarget = conditionConfig.values.includes(sourceValue);
	    }
	    //there is no xor in js :-(
	    if (conditionConfig.invert) {
		showTarget = !contains;
	    }

	    // show or disable element
	    if (conditionConfig.disable) {
		targetElement.querySelectorAll(':where(input,select,textarea)').forEach((el) => el.disabled = showTarget);
	    } else {
		targetElement.style.display = showTarget ? 'block' : 'none';
	    }
	});
    }
};
IGDATAPOOLFE.addPlugin('condition', conditionPlugin);
export default conditionPlugin;
