// COPYRIGHT ANSYS. ALL RIGHTS RESERVED //


define(
    'scripts/css',
    ['scripts/knockout-3.3.0'],
    function (ko) {

        var stylesheets = [];

        function css(moduleNames, callback) {

            var loaded = false,
                loadedObservable = ko.observable(false);

            moduleNames.forEach(function (href) {
                if (stylesheets.indexOf(href) === -1) {
                    $('head').append('<link rel="stylesheet" type="text/css" href="' + href + '.css"/>');
                }
            });

            stylesheets = stylesheets.concat(moduleNames);

            (function poll() {

                loaded = moduleNames.every(function (href) {
                    var re = new RegExp(href + '.css$');
                    return Array.prototype.some.call(document.styleSheets, function (stylesheet) {
                        return re.test(stylesheet.href);
                    });
                });

                if (loaded) {
                    loadedObservable(true);
                    if (callback instanceof Function) {
                        callback(moduleNames);
                    }
                } else {
                    setTimeout(poll, 0);
                }
            })();

            return Object.freeze({
                get loaded() {
                    return loaded;
                },
                get hrefs() {
                    return moduleNames;
                },
                get loadedObservable() {
                    return loadedObservable;
                }
            });
        }

        return css;
    });