
const MUTATION_REFRESH_CHECK = 3000;

const DOM_IDS = ["probabilityPopup", "commentSection", "commentSectionHeader", "commentSectionBody"]

export default class PageMutationHandler {

    lastMutation: number;
    observer: MutationObserver;
    mutationHasOccured: boolean

    onPageMutation: Function;

    constructor(onPageMutation: Function) {
        this.onPageMutation = onPageMutation
    }

    init() {
        this.lastMutation = Date.now();
        this.observer = new MutationObserver((records) => {
            let watchedPageHasMutated = true;
            for (const record of records) {
                for (const id of Object.values(DOM_IDS)) {
                    const element = document.getElementById(id)
                    if (element && element.contains(record.target)) {
                        watchedPageHasMutated = false;
                        break;
                    }
                }
                if (!watchedPageHasMutated) {
                    break
                }
            }
            if (watchedPageHasMutated) {
                this.mutationHasOccured = true;
            }
        });
        let config = { attributes: true, childList: true, characterData: true, subtree: true};
        this.observer.observe(document.body, config);

        setInterval(() => {
            if (this.mutationHasOccured) {
                this.onPageMutation()
            }    
        }, MUTATION_REFRESH_CHECK)
    }
}