import { onPageLoadComplete } from '@nimius/event-utility';
import { Integrations } from '../../Scripts/toubiz-date-picker/integrations';
import { listenForAddedElements } from '@nimius/dom-utility';

/**
 * @param {HTMLElement} node
 */
export function initializeIntegrations(node) {
    for (const Integration of Integrations) {
        if (Integration.test(node)) {
            new Integration(node);
        }
    }
}

/**
 * @returns {Promise}
 */
async function lazyLoadDatePicker() {
    const { default: ToubizDatePicker } = await import(
        /* webpackChunkName: "toubiz-date-picker" */ '../../Scripts/toubiz-date-picker'
    );
    return ToubizDatePicker;
}

onPageLoadComplete(() => {
    listenForAddedElements(
        { selector: '[data-toubiz-date-picker]', checkForExistingNodes: true },
        node => lazyLoadDatePicker().then(ToubizDatePicker => {
            new ToubizDatePicker(node);
            initializeIntegrations(node);
        })
    );
});
