import { extractPrefixedAttributesFromElement } from '@nimius/dom-utility';

export default class ToubizStickyElement {

    /**
     * @param {HTMLElement} node
     */
    constructor(node) {
        const config = extractPrefixedAttributesFromElement(node, 'data-toubiz-sticky-element-');

        /** @private {HTMLElement} */
        this.node = node;

        /** @private {boolean} */
        this.isActive = config.active === 'true';

        /** @private {number} */
        this.switchPoint = parseFloat(node.offsetTop);

        /** @private {HTMLDivElement} */
        this.whitespaceFixElement = document.createElement('div');

        this.bindScroll();
        this.bindResize();

        /**
         * Insert another node after the sticky element with same height.
         * Prevents a scroll position jump when fixed position is activated.
         */
        this.setWhitespaceFixElementHeight();

        // Activate if it was set to true initially.
        if (this.isActive) {
            this.toggle(true);
        }
    }

    setWhitespaceFixElementHeight() {
        this.whitespaceFixElement.setAttribute('data-toubiz-sticky-element-whitespace', '');
        this.whitespaceFixElement.style.height = `${this.node.clientHeight}px`;
        this.node.parentNode.insertBefore(this.whitespaceFixElement, this.node.nextSibling);
    }

    toggle(active) {
        this.isActive = active;
        this.node.setAttribute('data-toubiz-sticky-element-active', active);
    }

    bindResize() {
        window.addEventListener('resize', () => {
            this.whitespaceFixElement.style.height = `${this.node.clientHeight}px`;
        });
    }

    bindScroll() {
        window.addEventListener('scroll', () => {
            const elementIsAboveThreshold = window.pageYOffset >= this.switchPoint;

            if (elementIsAboveThreshold && !this.isActive) {
                this.toggle(true);
            } else if (!elementIsAboveThreshold && this.isActive) {
                this.toggle(false);
            }
        });
    }

}

