var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { TaskQueue, autoinject } from 'aurelia-framework';
import { I18N } from 'aurelia-i18n';
import { GlobalLoaderService } from './global-loader-service';
import { HttpClient } from 'aurelia-fetch-client';
import { bindable } from 'aurelia-templating';
import { EventAggregator } from 'aurelia-event-aggregator';
import { observable } from 'aurelia-binding';
import { UIInternal } from '../../utils/ui-internal';
export var GlobalLoader = (function () {
    function GlobalLoader(eventAggregator, httpClient, element, service, i18n, taskQueue) {
        var _this = this;
        this.element = element;
        this.service = service;
        this.i18n = i18n;
        this.taskQueue = taskQueue;
        this.startDelay = 1000;
        this.progressValue = 0;
        this.success = true;
        this.displayed = false;
        this.pendingRequests = [];
        this.requestFn = function (request) {
            _this.start(request);
            return request;
        };
        this.requestErrorFn = function (error) {
            _this.done(false, null);
            return error;
        };
        this.responseFn = function (response) {
            _this.done(response.status == 200, response.url);
            return response;
        };
        this.responseErrorFn = function (error) {
            _this.done(false, null);
            return error;
        };
        eventAggregator.subscribe('flow:uploading', function (e) { return _this.start(e); });
        eventAggregator.subscribe('flow:progress', this.progress);
        eventAggregator.subscribe('flow:complete', function (e) { return _this.done(true, e === null || e === void 0 ? void 0 : e.url); });
        UIInternal.subscribe(UIInternal.EVT_GLOBAL_LOADER_SHOW, function () { return _this.show(); });
        UIInternal.subscribe(UIInternal.EVT_GLOBAL_LOADER_HIDE, function () { return _this.hide(); });
        httpClient.configure(function (config) {
            config.withInterceptor({
                request: _this.requestFn,
                requestError: _this.requestErrorFn,
                response: _this.responseFn,
                responseError: _this.responseErrorFn
            });
        });
    }
    GlobalLoader.prototype.progress = function (value) {
        this.progressValue = value;
    };
    GlobalLoader.prototype.start = function (request) {
        var _this = this;
        var _a, _b, _c, _d;
        if (!((_a = this.service) === null || _a === void 0 ? void 0 : _a.allowToShowGlobalLoader) || ((_c = (_b = this.service) === null || _b === void 0 ? void 0 : _b.forceShow) !== null && _c !== void 0 ? _c : true))
            return;
        if (this.startTimer)
            clearTimeout(this.startTimer);
        this.success = true;
        this.displayed = true;
        if (this.progressValue > 101)
            this.progressValue = 1;
        this.startTimer = setTimeout(function () {
            _this.pendingRequests.push(request.url);
            _this.show();
        }, (((_d = this.service) === null || _d === void 0 ? void 0 : _d.delay) != null ? this.service.delay : parseInt(this.startDelay.toString())));
    };
    GlobalLoader.prototype.done = function (success, responseUrl) {
        var _this = this;
        var _a, _b;
        if (success === void 0) { success = true; }
        if ((_b = (_a = this.service) === null || _a === void 0 ? void 0 : _a.forceShow) !== null && _b !== void 0 ? _b : true)
            return;
        this.doneTimer = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.clearPendingRequest(responseUrl);
                        clearTimeout(this.startTimer);
                        clearTimeout(this.progressTimer);
                        if (!(this.displayed && (this.pendingRequests.length == 0 || !success))) return [3, 2];
                        this.progressValue = 102;
                        this.success = success;
                        this.element.classList.add('done');
                        return [4, this.swapTextOff(success)];
                    case 1:
                        _a.sent();
                        this.displayed = false;
                        this.success = true;
                        this.hide();
                        this.service.reset();
                        _a.label = 2;
                    case 2: return [2];
                }
            });
        }); }, 100);
    };
    GlobalLoader.prototype.clearPendingRequest = function (url) {
        var index = this.pendingRequests.findIndex(function (x) { return x = url; });
        if (index > -1) {
            this.pendingRequests.splice(index, 1);
        }
    };
    GlobalLoader.prototype.swapTextOff = function (success) {
        var _this = this;
        if (success === void 0) { success = true; }
        return new Promise(function (res, rej) {
            var _a;
            if (_this.textEl != null && ((_a = _this.textEl.innerText) === null || _a === void 0 ? void 0 : _a.trim().length) > 0) {
                _this.taskQueue.queueTask(function () {
                    _this.textEl.innerHTML = success ? _this.i18n.tr('global-loader.done') : _this.i18n.tr('global-loader.error');
                    setTimeout(function () { return res(true); }, 800);
                });
            }
            else {
                setTimeout(function () { return res(true); }, 200);
            }
        });
    };
    GlobalLoader.prototype.show = function () {
        var _a;
        (_a = this.element) === null || _a === void 0 ? void 0 : _a.classList.add('show');
        this.initImage();
        this.initText();
        this.initProgress();
    };
    GlobalLoader.prototype.hide = function () {
        var _this = this;
        this.taskQueue.queueTask(function () {
            var _a, _b;
            (_a = _this.element) === null || _a === void 0 ? void 0 : _a.classList.remove('show');
            (_b = _this.element) === null || _b === void 0 ? void 0 : _b.classList.remove('progress');
            if (_this.textEl) {
                _this.textEl.classList.remove('off');
                _this.textEl.innerHTML = "";
            }
            _this.element.classList.remove('done');
        });
    };
    GlobalLoader.prototype.initText = function () {
        var _a, _b;
        if (((_b = (_a = this.service) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.trim().length) == 0)
            return;
        if (!this.textEl)
            return;
        this.textEl.innerHTML = this.i18n.tr(this.service.text);
    };
    GlobalLoader.prototype.initImage = function () {
        if (this.imgSrc == null)
            return;
        if (!this.imageEl)
            return;
        this.imageEl.src = this.imgSrc;
    };
    GlobalLoader.prototype.initProgress = function () {
        var _this = this;
        this.progressTimer = setTimeout(function () {
            _this.inc();
            if (_this.progressValue < 102)
                _this.initProgress();
        }, 200);
    };
    GlobalLoader.prototype.inc = function (amount) {
        if (amount === void 0) { amount = null; }
        if (this.progressValue == 101)
            this.progressValue = 1;
        var n = this.progressValue;
        if (n == null) {
            return null;
        }
        else if (n > 101) {
            return;
        }
        else {
            if (typeof amount !== 'number') {
                if (n >= 0 && n < 20) {
                    amount = 3;
                }
                else if (n >= 20 && n < 40) {
                    amount = 2;
                }
                else if (n >= 40 && n < 54) {
                    amount = 1;
                }
                else if (n >= 54 && n < 80) {
                    amount = 2;
                }
                else if (n >= 80 && n < 102) {
                    amount = 1;
                }
                else {
                    amount = 0;
                }
            }
            n = this.clamp(n + amount, 0, 101);
            return this.progressValue = n;
        }
    };
    ;
    GlobalLoader.prototype.clamp = function (n, min, max) {
        if (n < min)
            return min;
        if (n > max)
            return max;
        return n;
    };
    __decorate([
        bindable,
        __metadata("design:type", Object)
    ], GlobalLoader.prototype, "startDelay", void 0);
    __decorate([
        bindable,
        __metadata("design:type", String)
    ], GlobalLoader.prototype, "imgSrc", void 0);
    __decorate([
        observable,
        __metadata("design:type", Object)
    ], GlobalLoader.prototype, "displayed", void 0);
    GlobalLoader = __decorate([
        autoinject,
        __metadata("design:paramtypes", [EventAggregator, HttpClient, Element, GlobalLoaderService, I18N, TaskQueue])
    ], GlobalLoader);
    return GlobalLoader;
}());

//# sourceMappingURL=global-loader.js.map
