import { GefestElement } from "./element";

// For protecting the set of elements from direct access
const elements: Set<GefestElement> = new Set();
export class GefestEngine {
    static register (element: GefestElement) : string {
        elements.add(element);
        // Generate GefestID for the element
        const gefestId = `gefest-${Math.random().toString(36).substr(2, 9)}`;
        element.setAttribute('data-gefest-id', gefestId);

        return gefestId;
    }

    static async activateOnClick(): Promise<void> {
        for (let element of elements) {
            const elementHTML = document.querySelectorAll(`[data-gefest-id="${element.gefestId}"]`);
            if (elementHTML.length > 0) {
                const htmlElement = elementHTML[0] as HTMLElement;
                htmlElement.onclick = element.onClick;
            }
        }
    }

    static async main(main : () => Promise<void>): Promise<void> {
        await main();
        await GefestEngine.activateOnClick();
    }
}