import { loadScript } from '../common/load-utilities';

export class ToubizSocialGrid {

    /**
     * Creates a social grid instance.
     *
     * @param {HTMLElement} node - node wrapping the social grid tagged by `data-toubiz-social-grid`
     */
    constructor(node) {
        /** @private {HTMLElement} */
        this.node = node;

        /** @private {boolean} */
        this.containsFacebookPosts = this.node.querySelector('[data-toubiz-social-grid-facebook-post]') !== null;

        /** @private */
        this.macyInstance = null;

        this.waitForDependencies()
            .then(([ { default: Macy } ]) => {
                if (this.containsFacebookPosts) {
                    // eslint-disable-next-line no-undef
                    FB.Event.subscribe('xfbml.render', () => {
                        this.initializeView(Macy);
                    });
                } else {
                    this.initializeView(Macy);
                }
            })
            .catch(error => {
                console.warn(error);
            });
    }

    onLoaded() {
        this.node.classList.add('tb-social-grid--loaded');
    }

    initializeView(Macy) {
        const container = this.node.querySelector('[data-toubiz-social-grid-items]');

        if (!container) {
            console.warn(
                `## ToubizSocialGrid Warning - Masonry Layout not available
                Container node for social grid items can not be found.
                Enable masonry by including [data-toubiz-social-grid-items] in your markup.`
            );
            this.onLoaded();
            return;
        }

        /*
         * This number (600) should to be identical to the one used as a breakpoint
         * in 'Styles/components-social-grid/_social-grid.scss'
         */
        if (window.innerWidth <= 600) {
            // Skip masonry layout on smaller screens (uses stacked layout).
            this.onLoaded();
            return;
        }

        this.macyInstance = new Macy({
            container,
            columns: 4,
            waitForImages: true,
            margin: 16,
            breakAt: {
                1024: 2,
                600: 1,
            },
        });

        this.macyInstance.on(this.macyInstance.constants.EVENT_IMAGE_COMPLETE, () => {
            /**
             * Macy doesn't always size the item container properly,
             * dispatch a delayed resize event to trigger a recalculation.
             */
            setTimeout(() => {
                const event = document.createEvent('HTMLEvents');
                event.initEvent('resize', true, false);
                window.dispatchEvent(event);
            }, 1000);

            this.onLoaded();
        });
    }

    waitForDependencies() {
        const loadPromises = [ import(/* webpackChunkName: "vendor.macy" */ 'macy') ];

        if (this.containsFacebookPosts) {
            loadPromises.push(loadScript('https://connect.facebook.net/de_DE/sdk.js#xfbml=1&version=v3.2', 'fb-sdk'));
        }

        return Promise.all(loadPromises);
    }

}
