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 __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { Injectable, Inject } from "@angular/core";
import { TranslationService } from "./translation.service";
import { HttpClient, HttpHeaders } from "@angular/common/http";
var PathService = /** @class */ (function () {
    function PathService(http, translationService) {
        this.http = http;
        this.translationService = translationService;
        this._alertStack = [];
        this._requestCount = 0;
    }
    PathService.prototype.isLoading = function () {
        return this._requestCount > 0;
    };
    PathService.prototype.showLoading = function () {
        var _this = this;
        window.setTimeout(function () {
            _this._requestCount++;
        }, 1);
    };
    PathService.prototype.hideLoading = function () {
        var _this = this;
        window.setTimeout(function () {
            _this._requestCount--;
        }, 1);
    };
    PathService.prototype.serverGet = function (server, url, processor, errorHandler) {
        var _this = this;
        if (url != null) {
            // fetch json data from url
            this.showLoading();
            this.http.get(server + url, { observe: "response", headers: this.appendHeaders() })
                .subscribe(function (data) {
                var jwt = data.headers.get("Authorization");
                if (jwt != null && jwt !== "") {
                    sessionStorage.setItem("pathAppId", data.headers.get("Authorization"));
                }
                else {
                    sessionStorage.removeItem("pathAppId");
                }
                processor(data.body);
            }, function (err) {
                if (errorHandler == null) {
                    _this.handleError(err);
                }
                else {
                    errorHandler(err);
                }
            }, function () {
                _this.hideLoading();
                console.log("server GET to " + server + url + " finished");
            });
        }
        else {
            // no url provided, therefore call processor without data
            processor(null);
        }
    };
    PathService.prototype.serverPost = function (server, url, data, processor, errorHandler) {
        var _this = this;
        if (url != null) {
            this.showLoading();
            this.http.post(server + url, data, { observe: "response", headers: this.appendHeaders() })
                .subscribe(function (responseData) {
                sessionStorage.setItem("pathAppId", responseData.headers.get("Authorization"));
                console.log(responseData);
                processor(responseData.body);
            }, function (err) {
                if (errorHandler == null) {
                    _this.handleError(err);
                }
                else {
                    errorHandler(err);
                }
            }, function () {
                _this.hideLoading();
                console.log("server POST to " + server + url + " finished:");
                console.log(data);
            });
        }
        else {
            // no url provided, therefore call processor without data
            processor(null);
        }
    };
    PathService.prototype.serverPut = function (server, url, data, processor) {
        var _this = this;
        if (url != null) {
            this.showLoading();
            this.http.put(server + url, data, { observe: "response", headers: this.appendHeaders() })
                .subscribe(function (responseData) {
                sessionStorage.setItem("pathAppId", responseData.headers.get("Authorization"));
                console.log(responseData);
                processor(responseData.body);
            }, function (err) {
                _this.handleError(err);
            }, function () {
                _this.hideLoading();
                console.log("server PUT to " + server + url + " finished:");
                console.log(data);
            });
        }
        else {
            // no url provided, therefore call processor without data
            processor(null);
        }
    };
    PathService.prototype.serverDelete = function (server, url, processor) {
        var _this = this;
        if (url != null) {
            this.showLoading();
            this.http.delete(server + url, { observe: "response", headers: this.appendHeaders() })
                .subscribe(function (data) {
                sessionStorage.setItem("pathAppId", data.headers.get("Authorization"));
                console.log(data);
                processor(data.body);
            }, function (err) {
                _this.handleError(err);
            }, function () {
                _this.hideLoading();
                console.log("server DELETE to " + server + url + " finished:");
            });
        }
        else {
            // no url provided, therefore call processor without data
            processor(null);
        }
    };
    PathService.prototype.handleError = function (err) {
        this.hideLoading();
        if (err.status === 405 && err.error["messageKey"] != null) {
            alert(this.translationService.getText(err.error["messageKey"], err.error["parameters"]));
        }
        else if (err.status === 401) {
            alert("Unauthorized. Please login again.");
            location.reload();
        }
        else {
            // general error
            if (err.error["error"] == null && err.error["title"] == null) {
                this.addAlert("Unkwown Error", "Please check server and internet connection: " + err.error);
            }
            else {
                this.addAlert(err.error["title"], err.error["error"]);
            }
            console.error(err);
        }
    };
    PathService.prototype.appendHeaders = function () {
        var headers = new HttpHeaders();
        headers = headers.append("Content-Type", "application/json");
        var jwt = sessionStorage.getItem("pathAppId");
        if (jwt != null) {
            headers = headers.append("Authorization", jwt);
        }
        return headers;
    };
    PathService.prototype.getAlerts = function () {
        return this._alertStack;
    };
    PathService.prototype.addAlert = function (title, text) {
        var alert = new Alert();
        alert.title = title;
        alert.text = text;
        this._alertStack.push(alert);
    };
    PathService.prototype.clearAlert = function (id) {
        for (var i = 0; i < this._alertStack.length; i++) {
            if (this._alertStack[i].id === id) {
                this._alertStack.splice(i, 1);
                break;
            }
        }
    };
    PathService = __decorate([
        Injectable(),
        __param(0, Inject(HttpClient)),
        __metadata("design:paramtypes", [HttpClient, TranslationService])
    ], PathService);
    return PathService;
}());
export { PathService };
var Alert = /** @class */ (function () {
    function Alert() {
        this._id = Date.now();
    }
    Object.defineProperty(Alert.prototype, "title", {
        get: function () {
            return this._title;
        },
        set: function (value) {
            this._title = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Alert.prototype, "text", {
        get: function () {
            return this._text;
        },
        set: function (value) {
            this._text = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Alert.prototype, "id", {
        get: function () {
            return this._id;
        },
        enumerable: false,
        configurable: true
    });
    return Alert;
}());
export { Alert };
//# sourceMappingURL=path.service.js.map