const MEMORIZE_JQUERY_EVENT_PROPERTY = "rcbJQueryEventListenerMemorize";

/**
 * We listen to the passed event and once that event got triggered, all event registrations
 * afterwards are automatically executed, too. This does not need another trigger again.
 *
 * You need to call this function as early as possible to catch all triggers.
 */
function memorizeJQueryEvent(doc: Document, element: any, eventName: string) {
    const memorizeProp = `${MEMORIZE_JQUERY_EVENT_PROPERTY}_${eventName}`;
    const { jQuery } = (doc.defaultView || (doc as any).parentWindow) as any;

    if (!jQuery) {
        return;
    }

    const { event, Event } = jQuery;

    if (!event || !Event || event[memorizeProp]) {
        return;
    }

    // TODO: shouldn't this be memorized to the element itself?
    Object.assign(event, {
        [memorizeProp]: new Promise<any[]>((resolve) =>
            jQuery(element).on(eventName, (...args: any[]) => resolve(args)),
        ),
    });
}

export { memorizeJQueryEvent, MEMORIZE_JQUERY_EVENT_PROPERTY };
