import {getGlobal} from "../../source/types/global.mjs";

const global = getGlobal();

export function setupIntersectionObserverMock(
    {
        root = null,
        rootMargin = '',
        thresholds = [],
        disconnect = () => null,
        observe = () => null,
        takeRecords = () => [],
        unobserve = () => null,
    } = {}) {

    const savedImplementation = window.IntersectionObserver;
    const savedGlobalImplementation = global.IntersectionObserver;

    let lastObject;

    class MockIntersectionObserver {
        constructor(callback, options) {
            this.root = root;
            this.rootMargin = rootMargin;
            this.thresholds = thresholds;
            this.disconnect = disconnect;
            this.observe = observe;
            this.takeRecords = takeRecords;
            this.unobserve = unobserve;
            this.callback = callback;
            this.options = options;

            lastObject = this;
        }

        enterNode() {

            const entries = [];
            entries.push({
                isIntersecting: true
            })

            this['callback'](entries, this);
        }


    }

    Object.defineProperty(window, 'IntersectionObserver', {
        writable: true,
        configurable: true,
        value: MockIntersectionObserver
    });

    Object.defineProperty(global, 'IntersectionObserver', {
        writable: true,
        configurable: true,
        value: MockIntersectionObserver
    });


    return {
        restore: function () {
            window.IntersectionObserver = savedImplementation;
            global.IntersectionObserver = savedGlobalImplementation;
        },
        getInstance: function () {
            return lastObject;
        }
    }
}
