import { getUserDecision } from "./getUserDecision.js";
import { CookieConsentManager } from "../apply/manager.js";
import { BANNER_PRE_DECISION_SHOW_EVENT } from "../events/bannerPredecisionShow.js";
import { OPT_IN_ALL_EVENT } from "../events/optInAll.js";

/**
 * Listen to opt-in so we can safely print the UUID of the current consent to HTML elements.
 */
function printConsentUuidsToHTMLElement(selector: string, decisionCookieName: string | CookieConsentManager) {
    const elements = Array.prototype.slice.call(document.querySelectorAll<HTMLSpanElement>(selector)) as HTMLElement[];

    document.addEventListener(BANNER_PRE_DECISION_SHOW_EVENT, (() => {
        elements.forEach((element) => (element.innerHTML = element.getAttribute("data-fallback")));
    }) as any);

    document.addEventListener(OPT_IN_ALL_EVENT, (() => {
        const consent = getUserDecision(
            decisionCookieName instanceof CookieConsentManager
                ? decisionCookieName.getOption("decisionCookieName")
                : decisionCookieName,
        );
        const allUuids = consent ? [consent.uuid, ...consent.previousUuids] : [];

        elements.forEach(
            (element) =>
                (element.innerHTML = allUuids.length > 0 ? allUuids.join(", ") : element.getAttribute("data-fallback")),
        );
    }) as any);
}

export { printConsentUuidsToHTMLElement };
