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 { json, HttpClient } from 'aurelia-fetch-client';
import { customElement, bindable, TaskQueue, inlineView, bindingMode, autoinject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { Config } from '../../config';
import tinymce from 'tinymce';
import { Guid } from './utilities/guid';
export var TinyMce = (function () {
    function TinyMce(element, taskQueue, router, config, httpClient) {
        var _this = this;
        this.element = element;
        this.taskQueue = taskQueue;
        this.config = config;
        this.httpClient = httpClient;
        this.theme = "silver";
        this.inline = false;
        this.content = '';
        this.readonly = false;
        this.editorId = '';
        this.editorInstance = null;
        this.isDestroying = false;
        this.images_upload_handler = function (blobInfo) { return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
            var folderName, result, uri;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        folderName = (_a = this.imageFolderName) !== null && _a !== void 0 ? _a : "tiny-mce/".concat(this.editorId);
                        return [4, this.httpClient.post(this.config.globalConfig.remoteServiceName + this.config.globalConfig.remoteTinyMceController + "uploadBase64?folderName=".concat(folderName, "&fileName=").concat(blobInfo.filename()), json(blobInfo.base64()))];
                    case 1:
                        result = _b.sent();
                        if (!result.ok) return [3, 3];
                        return [4, result.json()];
                    case 2:
                        uri = _b.sent();
                        return [2, resolve(uri)];
                    case 3: return [2, reject("failed to upload to image")];
                }
            });
        }); }); };
        this.setBaseUrl(router);
    }
    TinyMce.prototype.bind = function () {
        this.options = Object.assign({}, this.config.defaultRichTextEditorOptions, this.options);
        this.setEditorId();
        if (this.inline !== false)
            this.inline = true;
    };
    TinyMce.prototype.attached = function () {
        var _this = this;
        this.taskQueue.queueMicroTask(function () {
            var el = _this.element.getElementsByClassName('tinymce-editor').item(0);
            el.removeAttribute('style');
            el.removeAttribute('aria-hidden');
            _this.options.target = el;
            _this.options.theme = _this.theme;
            _this.options.mobile = {
                theme: _this.theme
            };
            _this.options.readonly = _this.readonly;
            _this.options.inline = _this.inline;
            _this.options.images_upload_handler = function (blobInfo) { return _this.images_upload_handler(blobInfo); };
            var save_init_instance_callback = _this.options.init_instance_callback;
            _this.options.init_instance_callback = function (editor) {
                editor.on('Change KeyUp', function (e) {
                    if (_this.isDestroying === true)
                        return;
                    _this.content = _this.getContent();
                });
                if (save_init_instance_callback) {
                    save_init_instance_callback(editor);
                }
                if (_this.editorInstance && _this.content) {
                    _this.setContent(_this.content);
                }
            };
            tinymce.init(_this.options);
            _this.editorInstance = tinymce.get(_this.options.target.id);
        });
    };
    TinyMce.prototype.detached = function () {
        try {
            if (this.editorInstance) {
                this.isDestroying = true;
                this.editorInstance.destroy();
            }
        }
        catch (error) {
            console.log('Error when detaching tinymce', error);
        }
    };
    TinyMce.prototype.setBaseUrl = function (router) {
        var _a;
        if (((_a = router === null || router === void 0 ? void 0 : router.options) === null || _a === void 0 ? void 0 : _a.root) != null) {
            if (router.options.root.startsWith('/')) {
                tinymce.baseURL = router.options.root + 'tinymce';
            }
            else {
                tinymce.baseURL = '/' + router.options.root + 'tinymce';
            }
        }
        else {
            tinymce.baseURL = '/tinymce';
        }
    };
    TinyMce.prototype.setEditorId = function () {
        var _this = this;
        this.taskQueue.queueMicroTask(function () {
            var guid = Guid.newGuid();
            _this.editorId = "editor-".concat(guid.toString());
        });
        this.taskQueue.flushMicroTaskQueue();
    };
    TinyMce.prototype.contentChanged = function (value) {
        if (value !== this.getContent())
            this.setContent(value);
    };
    TinyMce.prototype.setContent = function (value) {
        if (this.editorInstance) {
            if (value == null)
                value = '';
            var el = document.createElement('html');
            el.innerHTML = value;
            var body = el.getElementsByTagName('body');
            var bodyHtml = body.item(0).innerHTML;
            this.editorInstance.setContent(bodyHtml);
        }
    };
    TinyMce.prototype.getContent = function () {
        if (this.editorInstance) {
            var innerContent = this.editorInstance.getContent();
            if (innerContent == null || innerContent.length == 0)
                return null;
            return $('#' + this.editorId).next().find('iframe').contents().find("html").html();
        }
    };
    TinyMce.prototype.readonlyChanged = function (readonly) {
        if (this.editorInstance) {
            if (readonly) {
                this.editorInstance.mode.set("readonly");
            }
            else {
                this.editorInstance.mode.set("design");
            }
        }
    };
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", String)
    ], TinyMce.prototype, "theme", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", Boolean)
    ], TinyMce.prototype, "inline", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.twoWay }),
        __metadata("design:type", String)
    ], TinyMce.prototype, "content", void 0);
    __decorate([
        bindable,
        __metadata("design:type", Boolean)
    ], TinyMce.prototype, "readonly", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", Object)
    ], TinyMce.prototype, "options", void 0);
    __decorate([
        bindable,
        __metadata("design:type", String)
    ], TinyMce.prototype, "imageFolderName", void 0);
    TinyMce = __decorate([
        inlineView("<template> \n<div>\n  <div id.bind=\"editorId\" class=\"tinymce-editor\"></div>\n</div>\n</template>"),
        customElement('tiny-mce'),
        autoinject,
        __metadata("design:paramtypes", [Element, TaskQueue, Router, Config, HttpClient])
    ], TinyMce);
    return TinyMce;
}());

//# sourceMappingURL=tiny-mce.js.map
