"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var app_1 = require("../app");
var TestResourceMaintainer = (function () {
    function TestResourceMaintainer() {
        var _this = this;
        this.scriptSrc = "/composer/R.js";
        this.styleSrc = "/composer/style/R.css";
        this.events = new Leaf.EventEmitter();
        this.isLoading = false;
        this.keepLoading = false;
        this.retryInterval = 1000;
        var meta = document.querySelector("meta[name='style']");
        if (meta) {
            this.styleSrc = meta.getAttribute("content");
        }
        meta = document.querySelector("meta[name='script']");
        if (meta) {
            this.scriptSrc = meta.getAttribute("content");
        }
        this.load();
        app_1.App.fileChangeNotificationService.events.listenBy(this, "change", function () {
            _this.load();
        });
    }
    TestResourceMaintainer.prototype.load = function () {
        var _this = this;
        if (this.isLoading) {
            this.keepLoading = true;
            return;
        }
        this.isLoading = true;
        if (this.script) {
            this.script.remove();
        }
        this.script = document.createElement("script");
        this.script.src = this.scriptSrc;
        this.events.emit("reloading");
        document.body.appendChild(this.script);
        this.script.addEventListener("load", function () {
            if (_this.style) {
                _this.style.remove();
            }
            var link = _this.style = document.createElement("link");
            link.setAttribute("rel", "stylesheet");
            link.setAttribute("href", _this.styleSrc);
            link.setAttribute("type", "text/css");
            document.body.appendChild(link);
            link.addEventListener("load", function () {
                _this.isLoading = false;
                if (_this.keepLoading) {
                    _this.keepLoading = false;
                    _this.load();
                    return;
                }
                _this.events.emit("reloaded");
            });
            link.addEventListener("error", function () {
                console.error("fail to load style, retry after", _this.retryInterval, "ms");
                setTimeout(function () {
                    _this.isLoading = false;
                    _this.load();
                }, _this.retryInterval);
            });
        });
        this.script.addEventListener("error", function () {
            console.error("fail to load script, retry after", _this.retryInterval, "ms");
            setTimeout(function () {
                _this.isLoading = false;
                _this.load();
            }, _this.retryInterval);
        });
    };
    return TestResourceMaintainer;
}());
exports.TestResourceMaintainer = TestResourceMaintainer;
