"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoteFileStorage = void 0;
var aurelia_fetch_client_1 = require("aurelia-fetch-client");
var aurelia_framework_1 = require("aurelia-framework");
var config_1 = require("./../config");
var RemoteFileStorage;
(function (RemoteFileStorage) {
    var Service = (function () {
        function Service() {
        }
        return Service;
    }());
    RemoteFileStorage.Service = Service;
    var ServiceValidator = (function () {
        function ServiceValidator() {
        }
        ServiceValidator.implementsInterface = function (service) {
            return service instanceof Service;
        };
        return ServiceValidator;
    }());
    RemoteFileStorage.ServiceValidator = ServiceValidator;
    var DWService = (function (_super) {
        __extends(DWService, _super);
        function DWService(httpClient, config) {
            var _this = _super.call(this) || this;
            _this.httpClient = httpClient;
            _this.config = config;
            _this.secure = _this.config.globalConfig.remoteFileStorageServiceConfig.secure || false;
            _this.controller = _this.config.globalConfig.remoteServiceName + _this.config.globalConfig.remoteFileStorageServiceConfig.controller;
            var canDownloadFiles = _this.config.globalConfig.remoteFileStorageServiceConfig.canDownloadFiles;
            _this.canDownloadFiles = canDownloadFiles == null ? !_this.secure : canDownloadFiles;
            _this.ignoreUris = _this.config.globalConfig.remoteFileStorageServiceConfig.ignoreUris || [];
            return _this;
        }
        DWService.prototype.download = function (fileName) {
            return __awaiter(this, void 0, void 0, function () {
                var req, blob, fileUrl, link;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.canDownloadFiles)
                                return [2];
                            return [4, this.httpClient.get(this.remoteFileReadUri + "?fileName=" + encodeURI(fileName))];
                        case 1:
                            req = _a.sent();
                            if (!(req != null)) return [3, 3];
                            return [4, req.blob()];
                        case 2:
                            blob = _a.sent();
                            fileUrl = window.URL.createObjectURL(blob);
                            link = document.createElement('a');
                            link.href = fileUrl;
                            link.download = fileName != null ? fileName.substring(fileName.lastIndexOf('/') + 1) : fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
                            link.click();
                            link.remove();
                            _a.label = 3;
                        case 3: return [2];
                    }
                });
            });
        };
        DWService.prototype.fileUrl = function (fileName) {
            return __awaiter(this, void 0, void 0, function () {
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (fileName == null || fileName.trim().length == 0)
                                return [2, null];
                            if ((!this.secure && fileName.startsWith("http")) || this.ignoreUris.some(function (uri) { return fileName.startsWith(uri); }))
                                return [2, fileName];
                            if (!this.secure) return [3, 2];
                            _a = this.remoteFilePreviewUri + "/";
                            return [4, this.previewToken()];
                        case 1: return [2, _a + (_b.sent()) + "?fileName=" + encodeURI(fileName)];
                        case 2: return [2, this.remoteFileReadUri + "?fileName=" + encodeURI(fileName)];
                    }
                });
            });
        };
        DWService.prototype.previewToken = function () {
            return __awaiter(this, void 0, void 0, function () {
                var req;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.httpClient.get(this.remoteFileGetTokenUri)];
                        case 1:
                            req = _a.sent();
                            if (!req.ok) return [3, 3];
                            return [4, req.text()];
                        case 2: return [2, (_a.sent())];
                        case 3: return [2];
                    }
                });
            });
        };
        DWService.prototype.rotate = function (fileName, clockwise) {
            if (clockwise === void 0) { clockwise = true; }
            return __awaiter(this, void 0, void 0, function () {
                var req;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (fileName == null || fileName.trim().length == 0)
                                return [2, null];
                            return [4, this.httpClient.post(this.remoteFileRotateUri, JSON.stringify({
                                    "uri": fileName,
                                    "clockwise": clockwise
                                }))];
                        case 1:
                            req = _a.sent();
                            if (!req.ok) return [3, 3];
                            return [4, req.text()];
                        case 2: return [2, (_a.sent())];
                        case 3: return [2];
                    }
                });
            });
        };
        DWService.prototype.duplicate = function (fileName, newFolderName) {
            return __awaiter(this, void 0, void 0, function () {
                var req;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (fileName == null || fileName.trim().length == 0)
                                return [2, null];
                            return [4, this.httpClient.post(this.remoteFileDuplicateUri, JSON.stringify({
                                    "uri": fileName,
                                    "folderName": newFolderName
                                }))];
                        case 1:
                            req = _a.sent();
                            if (!req.ok) return [3, 3];
                            return [4, req.text()];
                        case 2: return [2, (_a.sent())];
                        case 3: return [2];
                    }
                });
            });
        };
        DWService.prototype.exists = function (fileName) {
            return __awaiter(this, void 0, void 0, function () {
                var req;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (fileName == null || fileName.trim().length == 0)
                                return [2, false];
                            return [4, this.httpClient.get(this.remoteFileExistsUri + '?fileName=' + fileName)];
                        case 1:
                            req = _a.sent();
                            if (!req.ok) return [3, 3];
                            return [4, req.json()];
                        case 2: return [2, (_a.sent())];
                        case 3: return [2];
                    }
                });
            });
        };
        DWService.prototype.uploadBase64 = function (fileName, dataBase64) {
            return __awaiter(this, void 0, void 0, function () {
                var req;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (fileName == null || fileName.trim().length == 0 || dataBase64 == null || dataBase64.trim().length == 0)
                                return [2, null];
                            return [4, this.httpClient.post(this.remoteFileUploadBase64 + '?fileName=' + fileName, JSON.stringify(dataBase64))];
                        case 1:
                            req = _a.sent();
                            if (!req.ok) return [3, 3];
                            return [4, req.json()];
                        case 2: return [2, (_a.sent()).Url];
                        case 3: return [2];
                    }
                });
            });
        };
        Object.defineProperty(DWService.prototype, "remoteFileControllerUri", {
            get: function () {
                return this.getRemoteActionUriByName('upload');
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DWService.prototype, "remoteFileExistsUri", {
            get: function () {
                return this.getRemoteActionUriByName('exists');
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DWService.prototype, "remoteFileRotateUri", {
            get: function () {
                return this.getRemoteActionUriByName('rotate');
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DWService.prototype, "remoteFileDuplicateUri", {
            get: function () {
                return this.getRemoteActionUriByName('duplicate');
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DWService.prototype, "remoteFileReadUri", {
            get: function () {
                return this.getRemoteActionUriByName('read');
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DWService.prototype, "remoteFileGetTokenUri", {
            get: function () {
                return this.getRemoteActionUriByName('token');
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DWService.prototype, "remoteFilePreviewUri", {
            get: function () {
                return this.getRemoteActionUriByName('preview');
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DWService.prototype, "remoteFileUploadBase64", {
            get: function () {
                return this.getRemoteActionUriByName('uploadbase64');
            },
            enumerable: false,
            configurable: true
        });
        DWService.prototype.getRemoteActionUriByName = function (name) {
            if (this.controller == null || this.controller.length == 0)
                return 'You must configure a remote file service controller uri';
            return "".concat(this.controller).concat(name);
        };
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFileControllerUri", null);
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFileExistsUri", null);
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFileRotateUri", null);
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFileDuplicateUri", null);
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFileReadUri", null);
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFileGetTokenUri", null);
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFilePreviewUri", null);
        __decorate([
            (0, aurelia_framework_1.computedFrom)('controller'),
            __metadata("design:type", Object),
            __metadata("design:paramtypes", [])
        ], DWService.prototype, "remoteFileUploadBase64", null);
        DWService = __decorate([
            (0, aurelia_framework_1.inject)(aurelia_fetch_client_1.HttpClient, config_1.Config),
            __metadata("design:paramtypes", [aurelia_fetch_client_1.HttpClient, config_1.Config])
        ], DWService);
        return DWService;
    }(Service));
    RemoteFileStorage.DWService = DWService;
})(RemoteFileStorage = exports.RemoteFileStorage || (exports.RemoteFileStorage = {}));

//# sourceMappingURL=file-storage-service.js.map
