var LOG_PREFIX = "[CBL.Serviços Loader]"
if (APP_URL == null) {
    APP_URL = "http://localhost:5000";
}
if (API_URL == null) {
    API_URL = "http://localhost:7071";
}

if (window.localStorage && window.localStorage["API_URL"]){
    API_URL = window.localStorage["API_URL"];
}

if (window.localStorage && window.localStorage["APP_URL"]){
    APP_URL = window.localStorage["APP_URL"];
}

const log = function () {
    var args = Array.prototype.slice.call(arguments);
    args.unshift(LOG_PREFIX + " ");
    console.log.apply(console, args);
}

if (!window.CBLReactLoaded) {
    var origin = APP_URL;
    fetch(origin + "/asset-manifest.json?k=" + Math.round(new Date().getTime() / 1000))
        .then(function (resp) {
            return resp.json()
        })
        .then(function (data) {
            var scriptsLoad = [];
            data.entrypoints.forEach(function (file) {
                if (file.indexOf(".css") != -1) {
                    var link = document.createElement('link');
                    link.id = "cramaincss";
                    link.rel = 'stylesheet';
                    link.type = 'text/css';
                    link.href = origin + "/" + file;
                    link.media = 'all';
                    document.body.appendChild(link);

                }
                else {
                    let promise = new Promise(function (resolve, reject) {
                        var bundle = document.createElement('script');
                        bundle.onload = function () { console.log(file + " loaded"); resolve(); };
                        bundle.setAttribute('type', "text/javascript");
                        bundle.setAttribute('src', origin + "/" + file);
                        document.body.appendChild(bundle);
                    });
                    scriptsLoad.push(promise);
                }
            })
            return Promise.all(scriptsLoad)
        })
        .then(function () {
            log("React App lodaded.");
            window.CBLReactLoaded = true;
            var modulesToRender = document.querySelectorAll('[data-react]');
            log("Modules to render: " + modulesToRender.length);
            modulesToRender.forEach(function (element) {                                
                var module = element.attributes["data-react"].value;                
                renderModuleIn(module, element, function() {
                    console.log("disable loading");
                    element.className = (element.className || "").replace("loading", "");
                });                
            });
        });
}