/**
 * Info popup bootstrap loader.
 *
 * Fetches the active, visible popups for the current session user as light
 * metadata, filters out already-seen entries and opens the remaining ones
 * sequentially. The complete popup markup is fetched per entry just before
 * it is shown - the window only opens once its HTML has arrived, so there
 * is no loader inside the popup.
 *
 * @module package/quiqqer/info-popup/bin/Popups
 * @author www.pcsg.de
 */
define('package/quiqqer/info-popup/bin/Popups', [

    'Ajax'

], function (QUIAjax) {
    "use strict";

    const STORAGE_PREFIX = 'quiqqer-infoPopup-seen-';

    /**
     * Was this exact entry version already seen (and closed)?
     *
     * @param {Object} entry
     * @return {boolean}
     */
    function isSeen(entry) {
        try {
            return window.localStorage.getItem(STORAGE_PREFIX + entry.id) === String(entry.editDate);
        } catch (e) {
            return false;
        }
    }

    /**
     * Remember the current entry version as seen.
     *
     * @param {Object} entry
     */
    function markSeen(entry) {
        try {
            window.localStorage.setItem(STORAGE_PREFIX + entry.id, String(entry.editDate));
        } catch (e) {
            // storage not available - ignore
        }
    }

    /**
     * Fetch the markup of the next queued popup and, once it is there, open it.
     * Chains to the following entry when the popup is closed.
     *
     * @param {Array} queue
     */
    function openNext(queue) {
        if (!queue.length) {
            return;
        }

        const entry = queue.shift();

        QUIAjax.get('package_quiqqer_info-popup_ajax_frontend_getPopupHtml', function (html) {
            // entry no longer visible / valid -> skip without marking it seen
            if (!html) {
                openNext(queue);
                return;
            }

            require(['package/quiqqer/info-popup/bin/controls/InfoPopup'], function (InfoPopup) {
                new InfoPopup({
                    html: html,
                    maxWidth: parseInt(entry.maxWidth) || 800,
                    maxHeight: parseInt(entry.maxHeight) || 600,
                    events: {
                        onClose: function () {
                            markSeen(entry);
                            openNext(queue);
                        }
                    }
                }).open();
            });
        }, {
            'package': 'quiqqer/info-popup',
            id: entry.id,
            projectName: QUIQQER_PROJECT.name,
            projectLanguage: QUIQQER_PROJECT.lang
        });
    }

    return {

        /**
         * Load the active popup metadata and start the queue.
         */
        load: function () {
            if (typeof QUIQQER_PROJECT === 'undefined') {
                return;
            }

            QUIAjax.get('package_quiqqer_info-popup_ajax_frontend_getActivePopups', function (entries) {
                if (!entries || !entries.length) {
                    return;
                }

                const queue = entries.filter(function (entry) {
                    return !isSeen(entry);
                });

                if (!queue.length) {
                    return;
                }

                // project-wide delay (seconds) before the first popup appears
                const delay = Math.max(0, parseInt(queue[0].timeout) || 0) * 1000;

                if (delay > 0) {
                    window.setTimeout(function () {
                        openNext(queue);
                    }, delay);

                    return;
                }

                openNext(queue);
            }, {
                'package': 'quiqqer/info-popup',
                projectName: QUIQQER_PROJECT.name,
                projectLanguage: QUIQQER_PROJECT.lang
            });
        }
    };
});
