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 };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { HttpClient } from 'aurelia-fetch-client';
import { customAttribute, autoinject, useView, bindable, bindingMode, BindingEngine } from "aurelia-framework";
import { DialogService, DialogController } from "aurelia-dialog";
import { UIPictureEdit } from "./ui-picture-edit";
import { Config } from '../../config';
import { RemoteFileStorage } from './../../services/file-storage-service';
import { UIInternal } from '../../utils/ui-internal';
export var UILightbox = (function () {
    function UILightbox(image, dialogService, httpClient, config, fileStorageService, bindingEngine) {
        this.image = image;
        this.dialogService = dialogService;
        this.httpClient = httpClient;
        this.config = config;
        this.fileStorageService = fileStorageService;
        this.bindingEngine = bindingEngine;
        this.imageType = "url";
        this.isBase64Prefixed = true;
        this.clickable = true;
        this.suspendObservers = false;
        this.disposables = [];
    }
    UILightbox.prototype.toPreviewUrl = function (url) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (url == null || url.trim().length == 0)
                            return [2, null];
                        if (!url.match('base64,')) return [3, 1];
                        _a = url;
                        return [3, 3];
                    case 1: return [4, this.fileStorageService.fileUrl(url)];
                    case 2:
                        _a = _b.sent();
                        _b.label = 3;
                    case 3: return [2, _a];
                }
            });
        });
    };
    UILightbox.prototype.attached = function () {
        return __awaiter(this, void 0, void 0, function () {
            var setImageSrc, srcObserver;
            var _a;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        setImageSrc = function () { return __awaiter(_this, void 0, void 0, function () {
                            var src, url, previewUrl_1;
                            var _this = this;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        src = this.image.getAttribute("src") || this.src;
                                        if (!(!(src === null || src === void 0 ? void 0 : src.startsWith("http")) || this.fileStorageService.secure)) return [3, 3];
                                        url = this.image.getAttribute("data-url");
                                        if (url == null) {
                                            url = src;
                                            if (url == null)
                                                return [2];
                                            this.image.setAttribute('data-url', url);
                                        }
                                        previewUrl_1 = " ";
                                        this.suspendObservers = true;
                                        this.image.src = previewUrl_1;
                                        if (!((url === null || url === void 0 ? void 0 : url.trim().length) > 0)) return [3, 2];
                                        return [4, this.toPreviewUrl(url)];
                                    case 1:
                                        previewUrl_1 = _a.sent();
                                        _a.label = 2;
                                    case 2:
                                        UIInternal.queueTask(function () {
                                            _this.image.setAttribute("src", previewUrl_1);
                                            if (_this.suspendObservers) {
                                                setTimeout(function () { return _this.suspendObservers = false; }, 500);
                                            }
                                        });
                                        return [3, 4];
                                    case 3:
                                        this.image.setAttribute("src", src);
                                        _a.label = 4;
                                    case 4: return [2];
                                }
                            });
                        }); };
                        return [4, setImageSrc()];
                    case 1:
                        _b.sent();
                        srcObserver = function (newValue, oldValue) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                if (newValue != oldValue && !this.suspendObservers) {
                                    this.suspendObservers = true;
                                    this.image.setAttribute('data-url', newValue);
                                    setImageSrc();
                                }
                                return [2];
                            });
                        }); };
                        (_a = this.disposables).splice.apply(_a, __spreadArray([0, this.disposables.length], [
                            this.bindingEngine.propertyObserver(this.image, "src").subscribe(function (newValue, oldValue) {
                                if (newValue != oldValue) {
                                    newValue = _this.image.getAttribute("src") || newValue;
                                    srcObserver(newValue, oldValue);
                                }
                            }),
                            this.bindingEngine.propertyObserver(this, "src").subscribe(srcObserver)
                        ], false));
                        if (this.clickable) {
                            this.image.onclick = function () { return __awaiter(_this, void 0, void 0, function () {
                                var url, previewUrl;
                                var _this = this;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            url = this.image.getAttribute("data-url");
                                            if (url == null) {
                                                url = this.image.getAttribute("src") || this.src;
                                                this.image.setAttribute('data-url', url);
                                            }
                                            return [4, this.toPreviewUrl(url)];
                                        case 1:
                                            previewUrl = _a.sent();
                                            this.dialogService.open({ viewModel: UILightboxModal, model: { previewSrc: previewUrl, src: url, pictures: this.pictures, caption: this.image.getAttribute("alt"), canEdit: this.canEdit, canDownload: this.canDownload, showName: this.showName, imageType: this.imageType }, lock: true }).whenClosed(function (closeResult) {
                                                if (!closeResult.wasCancelled && _this.imageType == "base64") {
                                                    var base64 = closeResult.output;
                                                    if (!_this.isBase64Prefixed) {
                                                        base64 = base64.substring(base64.indexOf(",") + 1);
                                                    }
                                                    _this.src = base64;
                                                }
                                            });
                                            return [2];
                                    }
                                });
                            }); };
                        }
                        return [2];
                }
            });
        });
    };
    UILightbox.prototype.detached = function () {
        var _a;
        (_a = this.disposables) === null || _a === void 0 ? void 0 : _a.forEach(function (x) { return x.dispose(); });
    };
    __decorate([
        bindable({ defaultBindingMode: bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UILightbox.prototype, "src", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.toView }),
        __metadata("design:type", Array)
    ], UILightbox.prototype, "pictures", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UILightbox.prototype, "canEdit", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UILightbox.prototype, "canDownload", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UILightbox.prototype, "showName", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UILightbox.prototype, "imageType", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", Boolean)
    ], UILightbox.prototype, "isBase64Prefixed", void 0);
    __decorate([
        bindable,
        __metadata("design:type", Boolean)
    ], UILightbox.prototype, "clickable", void 0);
    UILightbox = __decorate([
        customAttribute("ui-lightbox"),
        useView(null),
        autoinject,
        __metadata("design:paramtypes", [Element, DialogService, HttpClient, Config, RemoteFileStorage.Service, BindingEngine])
    ], UILightbox);
    return UILightbox;
}());
export var UILightboxModal = (function () {
    function UILightboxModal(dialogController, dialogService, fileStorageService) {
        this.dialogController = dialogController;
        this.dialogService = dialogService;
        this.fileStorageService = fileStorageService;
        this.imageType = "url";
    }
    Object.defineProperty(UILightboxModal.prototype, "fileName", {
        get: function () {
            var _a, _b;
            if (this.pictures.length == 0) {
                return '';
            }
            return (_b = (_a = this.pictures[this.currentIndex]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : '';
        },
        enumerable: false,
        configurable: true
    });
    UILightboxModal.prototype.activate = function (model) {
        this.src = model.previewSrc;
        this.pictures = model.pictures;
        this.caption = model.caption;
        this.canEdit = model.canEdit;
        this.canDownload = model.canDownload;
        this.showName = model.showName;
        this.imageType = model.imageType;
        if (this.pictures != null && this.pictures.length > 0) {
            this.currentIndex = this.pictures.findIndex(function (x) { return x.url == model.src; });
        }
    };
    UILightboxModal.prototype.attached = function () {
        var _this = this;
        if (this.currentIndex != null) {
            this.handleShortcutsEvent = function (event) {
                if (event.key == "ArrowRight") {
                    event.stopImmediatePropagation();
                    event.preventDefault();
                    _this.nextPicture();
                }
                else if (event.key == "ArrowLeft") {
                    event.stopImmediatePropagation();
                    event.preventDefault();
                    _this.previousPicture();
                }
            };
            document.addEventListener("keydown", this.handleShortcutsEvent, false);
        }
    };
    UILightboxModal.prototype.detached = function () {
        if (this.currentIndex != null) {
            document.removeEventListener("keydown", this.handleShortcutsEvent, false);
        }
    };
    UILightboxModal.prototype.previousPicture = function () {
        return __awaiter(this, void 0, void 0, function () {
            var previewUrl;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.image.classList.remove("slide-left");
                        this.image.classList.remove("slide-right");
                        this.currentIndex = (this.currentIndex <= 0 ? this.pictures.length : this.currentIndex) - 1;
                        return [4, this.fileStorageService.fileUrl(this.pictures[this.currentIndex].url)];
                    case 1:
                        previewUrl = _a.sent();
                        this.src = previewUrl;
                        this.image.classList.add("slide-left");
                        setTimeout(function () {
                            _this.image.classList.remove("slide-left");
                        }, 250);
                        this.caption = null;
                        return [2];
                }
            });
        });
    };
    UILightboxModal.prototype.nextPicture = function () {
        return __awaiter(this, void 0, void 0, function () {
            var previewUrl;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.image.classList.remove("slide-left");
                        this.image.classList.remove("slide-right");
                        this.currentIndex = (this.currentIndex == this.pictures.length - 1 ? 0 : this.currentIndex + 1);
                        return [4, this.fileStorageService.fileUrl(this.pictures[this.currentIndex].url)];
                    case 1:
                        previewUrl = _a.sent();
                        this.src = previewUrl;
                        this.image.classList.add("slide-right");
                        setTimeout(function () {
                            _this.image.classList.remove("slide-right");
                        }, 250);
                        this.caption = null;
                        return [2];
                }
            });
        });
    };
    UILightboxModal.prototype.editPicture = function () {
        return __awaiter(this, void 0, void 0, function () {
            var previewUrl;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.fileStorageService.fileUrl(this.pictures[this.currentIndex].url)];
                    case 1:
                        previewUrl = _a.sent();
                        return [4, this.dialogService.open({ viewModel: UIPictureEdit, model: { url: (this.currentIndex != null ? this.pictures[this.currentIndex].url : this.src), previewUrl: previewUrl, type: this.imageType }, lock: true }).whenClosed(function (closeResult) { return __awaiter(_this, void 0, void 0, function () {
                                var cache;
                                var _a;
                                return __generator(this, function (_b) {
                                    switch (_b.label) {
                                        case 0:
                                            if (!!closeResult.wasCancelled) return [3, 5];
                                            return [4, caches.open("pictures")];
                                        case 1:
                                            cache = _b.sent();
                                            this.src = null;
                                            if (!(this.currentIndex != null)) return [3, 3];
                                            this.pictures[this.currentIndex].url = null;
                                            if (this.imageType == "url") {
                                                cache.delete(closeResult.output);
                                                cache.add(closeResult.output);
                                            }
                                            this.pictures[this.currentIndex].url = closeResult.output;
                                            return [4, this.fileStorageService.fileUrl(this.pictures[this.currentIndex].url)];
                                        case 2:
                                            previewUrl = _b.sent();
                                            this.pictures[this.currentIndex].previewSrc = previewUrl;
                                            (_a = this.pictures[this.currentIndex].entityAspect) === null || _a === void 0 ? void 0 : _a.rejectChanges();
                                            return [3, 4];
                                        case 3:
                                            if (this.imageType == "url") {
                                                cache.delete(closeResult.output);
                                                cache.add(closeResult.output);
                                            }
                                            _b.label = 4;
                                        case 4:
                                            this.src = previewUrl;
                                            _b.label = 5;
                                        case 5: return [2];
                                    }
                                });
                            }); })];
                    case 2:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    UILightboxModal.prototype.download = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.fileStorageService.download(this.pictures[this.currentIndex].name);
                return [2];
            });
        });
    };
    UILightboxModal = __decorate([
        useView('./ui-lightbox.html'),
        autoinject,
        __metadata("design:paramtypes", [DialogController, DialogService, RemoteFileStorage.Service])
    ], UILightboxModal);
    return UILightboxModal;
}());

//# sourceMappingURL=ui-lightbox.js.map
