"use strict";
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 __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
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));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UIChat = void 0;
var aurelia_router_1 = require("aurelia-router");
var communication_hub_client_1 = require("./../../services/signalr/communication-hub-client");
var custom_logger_1 = require("./../../modules/custom-logger");
var aurelia_framework_1 = require("aurelia-framework");
var aurelia_fetch_client_1 = require("aurelia-fetch-client");
var Tribute_js_1 = __importDefault(require("tributejs/src/Tribute.js"));
var service_base_1 = require("../../data/service-base");
var auth_service_1 = require("../../security/auth-service");
var constants_1 = require("./../../constants/constants");
var config_1 = require("../../config");
var moment_1 = __importDefault(require("moment"));
var UIChat = exports.UIChat = (function () {
    function UIChat(router, config, httpClient, authService, taskQueue, logger, commHubclient) {
        var _this = this;
        this.router = router;
        this.config = config;
        this.httpClient = httpClient;
        this.taskQueue = taskQueue;
        this.logger = logger;
        this.commHubclient = commHubclient;
        this.messageToSend = "";
        this.messageToEdit = "";
        this.disposables = [];
        this.signalRMethodName = function () { return "new-message-".concat(_this.entityName, "-").concat(_this.entityId); };
        this.keydownHandler = function (ev) { return _this.enter(ev); };
        this.userService = new service_base_1.ServiceBase(constants_1.EntityTypeNames.User);
        this.isLoading = false;
        this.messageList = [];
        this.messageToDisplay = [];
        this.authService = authService;
    }
    UIChat.prototype.bind = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getFirstMessageId()];
                    case 1:
                        _a.sent();
                        return [4, this.refreshChat(false)];
                    case 2:
                        _a.sent();
                        this.inputElement.addEventListener("keydown", this.keydownHandler);
                        return [4, this.buildTributeUsers(this.inputElement)];
                    case 3:
                        _a.sent();
                        this.commHubclient.subscribeToTopic(this.signalRMethodName());
                        this.disposables.push(this.commHubclient.onNewMessage(function (topic, data) {
                            _this.messageList.push(data);
                            _this.messagesCounter = _this.messageList.length;
                            if (_this.messageToDisplay.length > 0) {
                                var lastGroup = _this.messageToDisplay[_this.messageToDisplay.length - 1];
                                lastGroup.push(data);
                                _this.queueScrollToBottom();
                            }
                            _this.refreshChat(false);
                        }));
                        this.queueScrollToBottom();
                        return [2];
                }
            });
        });
    };
    UIChat.prototype.detached = function () {
        this.inputElement.removeEventListener('keydown', this.keydownHandler);
    };
    UIChat.prototype.unbind = function () {
        this.commHubclient.unsubscribeToTopic(this.signalRMethodName());
        this.disposables.forEach(function (x) { return x.dispose(); });
    };
    UIChat.prototype.attached = function () {
        return __awaiter(this, void 0, void 0, function () {
            var ce;
            var _this = this;
            return __generator(this, function (_a) {
                this.inputElement.onfocus = function () {
                    window.setTimeout(function () {
                        var sel, range;
                        if (window.getSelection && document.createRange) {
                            range = document.createRange();
                            range.selectNodeContents(_this.inputElement);
                            sel = window.getSelection();
                            sel.removeAllRanges();
                            range.collapse(false);
                            sel.addRange(range);
                        }
                    }, 1);
                };
                this.inputElement.focus();
                ce = document.querySelector('[contenteditable]');
                ce.addEventListener('paste', function (e) {
                    e.preventDefault();
                    var paste = e.clipboardData.getData('text/plain');
                    var selection = window.getSelection();
                    if (!selection.rangeCount)
                        return;
                    selection.deleteFromDocument();
                    selection.getRangeAt(0).insertNode(document.createTextNode(paste));
                    selection.collapseToEnd();
                });
                return [2];
            });
        });
    };
    UIChat.prototype.refreshChat = function (showLoading, scrollPosition) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.messageList.splice(0);
                        this.messageToDisplay.splice(0);
                        if (!(this.entityId != null && this.entityName != null)) return [3, 2];
                        return [4, this.getMessages(showLoading)];
                    case 1:
                        _a.sent();
                        this.messagesCounter = this.messageList.length;
                        _a.label = 2;
                    case 2:
                        if (scrollPosition != null) {
                            this.taskQueue.queueTask(function () {
                                _this.container.scrollTop = scrollPosition;
                            });
                        }
                        else {
                            this.taskQueue.queueTask(function () {
                                _this.container.scrollTop = _this.container.scrollHeight;
                            });
                        }
                        return [2];
                }
            });
        });
    };
    UIChat.prototype.enter = function (event) {
        var _a;
        if (event.key === constants_1.KeyboardShortcut.Enter && !((_a = this.tribute) === null || _a === void 0 ? void 0 : _a.isActive) && event.shiftKey === false) {
            event.preventDefault();
            document.getElementById("sendMessageButton").click();
        }
    };
    UIChat.prototype.queueScrollToBottom = function () {
        var _this = this;
        this.taskQueue.queueTask(function () {
            _this.container.scrollTop = _this.container.scrollHeight - _this.container.offsetHeight;
        });
    };
    UIChat.prototype.getData = function () {
        var _this = this;
        if (this.messageList.length > 0) {
            var lastMessageId_1 = this.getLastMessageId();
            this.getMessages(true, lastMessageId_1).then(function (result) {
                if (result) {
                    _this.taskQueue.queueTask(function () {
                        if (lastMessageId_1 != null) {
                            var lastMessage = document.getElementById(lastMessageId_1.toString());
                            if (lastMessage) {
                                _this.container.scrollTop = lastMessage.offsetTop;
                            }
                        }
                    });
                }
            });
        }
    };
    UIChat.prototype.getMessages = function (showLoading, lastMessageId) {
        if (lastMessageId === void 0) { lastMessageId = null; }
        return __awaiter(this, void 0, void 0, function () {
            var response, messages;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (lastMessageId == null) {
                            lastMessageId = this.getLastMessageId();
                        }
                        if (!(this.firstMessageId != null && this.firstMessageId != lastMessageId)) return [3, 6];
                        if (showLoading)
                            this.isLoading = true;
                        return [4, this.httpClient.fetch(this.config.globalConfig.remoteServiceName + "/api/communication/messages" + "?entityId=" + this.entityId + "&entityName=" + this.entityName + "&lastMessageId=" + (lastMessageId === null || lastMessageId === void 0 ? void 0 : lastMessageId.toString()))];
                    case 1:
                        response = _b.sent();
                        if (!response.ok) return [3, 3];
                        return [4, response.json()];
                    case 2:
                        messages = _b.sent();
                        (_a = this.messageList).unshift.apply(_a, __spreadArray([], __read(messages), false));
                        this.orderMessageList();
                        return [3, 5];
                    case 3: return [4, this.handleBadRequest(response)];
                    case 4:
                        _b.sent();
                        _b.label = 5;
                    case 5:
                        if (showLoading)
                            this.isLoading = false;
                        return [2, response.ok];
                    case 6: return [2, false];
                }
            });
        });
    };
    UIChat.prototype.getLastMessageId = function () {
        var _a;
        if (((_a = this.messageList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            return Math.min.apply(Math, __spreadArray([], __read(this.messageList.map(function (x) { return x.id; })), false));
        }
        return null;
    };
    UIChat.prototype.getFirstMessageId = function () {
        return __awaiter(this, void 0, void 0, function () {
            var results, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4, this.httpClient.fetch(this.config.globalConfig.remoteServiceName + "/api/communication/firstMessageId" + "?entityId=" + this.entityId + "&entityName=" + this.entityName)];
                    case 1:
                        results = _b.sent();
                        if (!results.ok) return [3, 3];
                        _a = this;
                        return [4, results.json()];
                    case 2:
                        _a.firstMessageId = (_b.sent());
                        return [3, 5];
                    case 3: return [4, this.handleBadRequest(results)];
                    case 4:
                        _b.sent();
                        _b.label = 5;
                    case 5: return [2];
                }
            });
        });
    };
    UIChat.prototype.handleBadRequest = function (response) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var errorReponse;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4, response.json()];
                    case 1:
                        errorReponse = _b.sent();
                        this.logger.LogError((_a = errorReponse["Message"]) !== null && _a !== void 0 ? _a : response.statusText, null, null, true);
                        return [2];
                }
            });
        });
    };
    UIChat.prototype.sendMessage = function () {
        return __awaiter(this, void 0, void 0, function () {
            var messageDTO, result, errorReponse;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.messageToSend.length > 0)) return [3, 4];
                        messageDTO = {
                            message: this.messageToSend,
                            messageId: null,
                            creatorId: this.authService.currentUser.id,
                            entityId: this.entityId,
                            entityName: this.entityName,
                            route: this.router.currentInstruction.fragment
                        };
                        return [4, this.httpClient.post(this.config.globalConfig.remoteServiceName + "/api/communication/messages", JSON.stringify(messageDTO))];
                    case 1:
                        result = _a.sent();
                        if (!result.ok) return [3, 2];
                        this.messageToSend = "";
                        this.inputElement.focus();
                        return [3, 4];
                    case 2: return [4, result.text()];
                    case 3:
                        errorReponse = _a.sent();
                        this.logger.LogError(errorReponse, null, null, true);
                        _a.label = 4;
                    case 4: return [2];
                }
            });
        });
    };
    UIChat.prototype.orderMessageList = function () {
        var _this = this;
        var lastCreatorId = 0;
        var lastTime;
        var messageGroup = [];
        this.messageToDisplay.splice(0);
        this.messageList.forEach(function (message) {
            if (lastCreatorId != message.createdById || lastTime == undefined || (0, moment_1.default)(message.createdTime).diff(lastTime, "h") > 1) {
                if ((0, moment_1.default)(message.createdTime).dayOfYear() != (0, moment_1.default)(lastTime).dayOfYear() || lastCreatorId == 0) {
                    message.firstMessageOfTheDay = true;
                }
                else {
                    message.firstMessageOfTheDay = false;
                }
                if (messageGroup.length > 0) {
                    _this.messageToDisplay.push(messageGroup);
                }
                messageGroup = [];
                lastCreatorId = message.createdById;
                lastTime = message.createdTime;
            }
            message.isMyMessage = _this.authService.currentUser.id == message.createdById;
            messageGroup.push(message);
        });
        this.messageToDisplay.push(messageGroup);
    };
    UIChat.prototype.onMouseOnMessage = function (message) {
        if (message.createdById == this.authService.currentUser.id) {
            message.showButton = true;
        }
    };
    UIChat.prototype.onMouseOutMessage = function (message) {
        message.showButton = false;
    };
    UIChat.prototype.deleteMessage = function (message) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.httpClient.delete(this.config.globalConfig.remoteServiceName + "/api/communication/messages/" + message.id.toString())];
                    case 1:
                        _a.sent();
                        this.refreshChat(false, this.container.scrollTop);
                        return [2];
                }
            });
        });
    };
    UIChat.prototype.editMessage = function (message) {
        message.showEdit = true;
        this.messageToEdit = message.messageML;
    };
    UIChat.prototype.sendEditMessage = function (message) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.httpClient.put(this.config.globalConfig.remoteServiceName + "/api/communication/messages/" + message.id.toString(), JSON.stringify(this.messageToEdit))];
                    case 1:
                        _a.sent();
                        message.showEdit = false;
                        this.messageToEdit = "";
                        this.refreshChat(false, this.container.scrollTop);
                        return [2];
                }
            });
        });
    };
    UIChat.prototype.cancelEditMessage = function (message) {
        message.showEdit = false;
        this.messageToEdit = "";
    };
    UIChat.prototype.getLocalTime = function (dateString, format) {
        return moment_1.default.utc(dateString).local().format(format).toString();
    };
    UIChat.prototype.buildTributeUsers = function (element) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, tributeValues;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this;
                        return [4, this.userService.getAllEntities()];
                    case 1:
                        _a.usersList = _b.sent();
                        tributeValues = [];
                        this.usersList.forEach(function (user) {
                            tributeValues.push({ id: user.id, name: "@" + user.fullName });
                        });
                        this.tribute = new Tribute_js_1.default({
                            values: tributeValues,
                            trigger: '@',
                            selectClass: "highlight",
                            selectTemplate: function (item) {
                                return "<span data-userid=".concat(item.original.id, " contenteditable=\"false\">").concat(item.original.name, "</span>");
                            },
                            menuItemTemplate: function (item) {
                                return (item.original.name.length > 70 ? item.original.name.substring(0, 70) + "..." : item.original.name);
                            },
                            lookup: 'name',
                            allowSpaces: true,
                            noMatchTemplate: function () {
                                return "";
                            },
                        });
                        this.tribute.attach(element);
                        return [2];
                }
            });
        });
    };
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", String)
    ], UIChat.prototype, "entityName", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Number)
    ], UIChat.prototype, "entityId", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.fromView }),
        __metadata("design:type", Number)
    ], UIChat.prototype, "messagesCounter", void 0);
    UIChat = __decorate([
        (0, aurelia_framework_1.customElement)('ui-chat'),
        aurelia_framework_1.autoinject,
        __metadata("design:paramtypes", [aurelia_router_1.Router, config_1.Config, aurelia_fetch_client_1.HttpClient, auth_service_1.AuthService, aurelia_framework_1.TaskQueue, custom_logger_1.CustomLogger, communication_hub_client_1.CommunicationHubClient])
    ], UIChat);
    return UIChat;
}());

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