/**
 * This class requires that [loadStyleSheet.js](http://thudjs.com/blog/loadStyleSheet.js) would be loaded before. A copy
 * of this file you can find [here](https://github.com/modera/ModeraMjrIntegrationBundle/tree/master/Resources/public/js/stylesheetsloader.js).
 *
 * [Here](http://thudjs.tumblr.com/post/637855087/stylesheetonload-or-lack-thereof)'s an article explaining some
 * problems with having CSS assets loaded with a callback upon completion.
 *
 * @author Sergei Lissovski <sergei.lissovski@modera.org>
 */
Ext.define('MF.misc.NonBlockingAssetsLoader', {
    requires: [
        'MF.misc.SyncedCallbackExecution',
        'Ext.Loader'
    ],

    /**
     * An array of JS files that must be loaded.
     *
     * @cfg {String[]} js
     */

    /**
     * An array of CSS files that must be loaded.
     *
     * @cfg {String[]} css
     */

    /**
     * Starts loading configured js/css assets, upon completion `onAllAssetsLoadedCallback` will be invoked.
     *
     * @param {Function} onAllAssetsLoadedCallback  Will be invoked when all given js/css assets have been loaded
     */
    startLoading: function(onAllAssetsLoadedCallback) {
        var me = this;

        var js = Ext.isArray(this.config.js) ? this.config.js : [],
            css = Ext.isArray(this.config.css) ? this.config.css : [];

        var asyncJoint = Ext.create('MF.misc.SyncedCallbackExecution', {
            expectedTotal: js.length + css.length,
            callback: function() {
                console.debug('%s.startLoading(): All assets were loaded :', me.$className, js.concat(css));

                onAllAssetsLoadedCallback();
            }
        });

        for (var i=0; i<js.length; i++) {
            Ext.Loader.loadScript({
                url: js[i],
                onLoad: asyncJoint.next,
                scope: asyncJoint
            });
        }

        for (var i=0; i<css.length; i++) {
            this.injectCss(css[i], function() {
                asyncJoint.next();
            });
        }
    },

    /**
     * @private
     *
     * @see http://thudjs.tumblr.com/post/637855087/stylesheetonload-or-lack-thereof
     *
     * @param {String} path
     * @param {Function} onResultCallback
     */
    injectCss: function(path, onResultCallback) {
        if (!window['loadStyleSheet']) {
            throw "'stylesheetsloader.js' is not installed, please see doc block of 'MF.misc.NonBlockingAssetsLoader' class for more details.";
        }

        window.loadStyleSheet(path, onResultCallback);
    },

    /**
     * @param {Object} config
     */
    constructor: function (config) {
        this.config = config;
    }
});