"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));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImportStep4 = exports.CustomDatasource = void 0;
var box_1 = require("./../../../modules/box");
var global_loader_service_1 = require("./../../../resources/global-loader/global-loader-service");
var aurelia_i18n_1 = require("aurelia-i18n");
var aurelia_framework_1 = require("aurelia-framework");
var aurelia_templating_resources_1 = require("aurelia-templating-resources");
var import_service_1 = require("../../service/import-service");
var import_correct_errors_1 = require("../../import-correct-errors/import-correct-errors");
var ui_internal_1 = require("../../../utils/ui-internal");
var CustomDatasource = (function () {
    function CustomDatasource(session, importService) {
        this.session = session;
        this.importService = importService;
    }
    CustomDatasource.prototype.getRowsForSelect2 = function (params, filterText, filterProperties) {
        return __awaiter(this, void 0, void 0, function () {
            var propertyName, list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        propertyName = params.sortModel[0].colId;
                        return [4, this.importService.getPossibleValues(this.session.contextName, this.session.id, propertyName)];
                    case 1:
                        list = (_a.sent()).sort(function (a, b) {
                            return a.localeCompare(b);
                        });
                        if ((filterText === null || filterText === void 0 ? void 0 : filterText.length) > 0) {
                            list = list.filter(function (l) { return l.toLocaleLowerCase().indexOf(filterText) >= 0; });
                        }
                        params.successCallback(list.map(function (v) {
                            var val = {};
                            val[propertyName] = v;
                            return val;
                        }), list.length);
                        return [2];
                }
            });
        });
    };
    return CustomDatasource;
}());
exports.CustomDatasource = CustomDatasource;
var ImportStep4 = exports.ImportStep4 = (function () {
    function ImportStep4(importService, globalLoader, i18n, bindingEngine, box, signaler) {
        this.importService = importService;
        this.globalLoader = globalLoader;
        this.i18n = i18n;
        this.bindingEngine = bindingEngine;
        this.box = box;
        this.signaler = signaler;
        this.importedRows = [];
        this.hideCorrectedError = true;
        this.dataIsLoaded = false;
        this.nbOfError = 0;
        this.technicalFields = ["errors", "isValid", "id", "importSessionId", "lineNr", "edit", "actions", "serverErrors"];
        this.disposables = [];
        this.displayContext = 'step4';
        this.selectedErrors = [];
    }
    ImportStep4.prototype.filter = function (data) {
        if (this.hideCorrectedError == true) {
            return !data.isValid && (data.ignoreRow == null || data.ignoreRow == false);
        }
        return true;
    };
    ImportStep4.prototype.hideCorrectedErrorChanged = function () {
        var _a;
        (_a = this.uiTableVM) === null || _a === void 0 ? void 0 : _a.filterChanged();
    };
    ImportStep4.prototype.toggleEdit = function (data) {
        data.edit = true;
    };
    Object.defineProperty(ImportStep4.prototype, "commonActions", {
        get: function () {
            var _a, _b;
            if (((_a = this.selectedErrors) === null || _a === void 0 ? void 0 : _a.length) == 0)
                return null;
            var intersections = this.selectedErrors[0].actions;
            var _loop_1 = function (index) {
                var nextElt = this_1.selectedErrors[index];
                intersections = intersections.filter(function (x) { var _a; return ((_a = nextElt.actions) === null || _a === void 0 ? void 0 : _a.findIndex(function (n) { return n.actionId == x.actionId; })) >= 0; });
            };
            var this_1 = this;
            for (var index = 1; index < ((_b = this.selectedErrors) === null || _b === void 0 ? void 0 : _b.length); index++) {
                _loop_1(index);
            }
            return intersections;
        },
        enumerable: false,
        configurable: true
    });
    ImportStep4.prototype.bind = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                setTimeout(function () {
                    _this.loadData();
                }, 800);
                setTimeout(function () {
                    $(_this.uiTable).on('select2:select', function (ev) {
                        var data = ev.params.data;
                        var uiSelectElt = ev.target.parentElement;
                        var uiSelect = uiSelectElt.au['ui-select'].viewModel;
                        var record = uiSelect === null || uiSelect === void 0 ? void 0 : uiSelect.parentContext.bindingContext;
                        var fieldName = uiSelect.optionsText;
                        if (!_this.floatingImportCorrectErrorsOpen) {
                            var existingError_1 = record.serverErrors.find(function (x) { return x.propertyName.toLowerCase() == fieldName.toLowerCase(); });
                            if (existingError_1 != null) {
                                var shouldDisplayCorrectErrorsBox = _this.importedRows.filter(function (x) { return !x.isValid && x[fieldName] == existingError_1.errorValue; }).length > 1;
                                if (shouldDisplayCorrectErrorsBox == true) {
                                    var box = new import_correct_errors_1.ImportCorrectErrors(_this.session, fieldName, record, _this.globalLoader, _this.importService, _this.errorTableView, _this.importedRows.filter(function (x) { return !x.isValid; }));
                                    _this.floatingImportCorrectErrorsOpen = true;
                                    _this.box.showFloatingBox(box).whenClosed(function () {
                                        ui_internal_1.UIInternal.nextTick(function () {
                                            _this.floatingImportCorrectErrorsOpen = false;
                                            _this.hideCorrectedErrorChanged();
                                            _this.nbOfError = _this.importedRows.filter(function (x) { return x.isValid == false; }).length;
                                            _this.importedRows.forEach(function (r) { return _this.assignErrorProperties(r); });
                                        });
                                    });
                                }
                            }
                        }
                    });
                }, 2000);
                return [2];
            });
        });
    };
    ImportStep4.prototype.loadData = function () {
        return __awaiter(this, void 0, void 0, function () {
            var importedRows;
            var _a;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.dataIsLoaded = false;
                        return [4, this.importService.getErrors(this.session.contextName, this.session.id)];
                    case 1:
                        importedRows = _b.sent();
                        this.listService = new CustomDatasource(this.session, this.importService);
                        this.importedRows.splice(0);
                        importedRows.forEach(function (r) {
                            r.edit = false;
                            _this.constructMenuItems(r);
                            Object.keys(r).filter(function (k) { return _this.technicalFields.indexOf(k) < 0; }).forEach(function (k, i) {
                                _this.disposables.push(_this.addPropertyObserver(r, k));
                            });
                            _this.assignErrorProperties(r);
                        });
                        (_a = this.importedRows).push.apply(_a, __spreadArray([], __read(importedRows), false));
                        this.dataIsLoaded = true;
                        this.nbOfError = this.importedRows.filter(function (x) { return x.isValid == false; }).length;
                        return [2];
                }
            });
        });
    };
    ImportStep4.prototype.unbind = function () {
        this.importedRows.splice(0);
        this.disposables.forEach(function (d) { return d.dispose(); });
    };
    ImportStep4.prototype.executeCommonAction = function (action) {
        var _this = this;
        var _a;
        if (((_a = this.selectedErrors) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            var promises_1 = [];
            this.selectedErrors.forEach(function (s) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
                return [2, promises_1.push(this.executeAction(s, action))];
            }); }); });
            Promise.all(promises_1);
            this.selectedErrors.splice(0);
        }
    };
    ImportStep4.prototype.openExcelFile = function () {
        window.open("https://view.officeapps.live.com/op/view.aspx?src=" + this.session.importFileSessions.fileUri, "_blank");
    };
    ImportStep4.prototype.executeAction = function (row, action) {
        return __awaiter(this, void 0, void 0, function () {
            var updatedRow;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.importService.executeAction(this.session.contextName, this.session.id, row.id, action.actionId)];
                    case 1:
                        updatedRow = _a.sent();
                        this.updateExistingRow(updatedRow);
                        return [2];
                }
            });
        });
    };
    ImportStep4.prototype.addPropertyObserver = function (row, prop) {
        var _this = this;
        return this.bindingEngine.propertyObserver(row, prop).subscribe(function (n, o) { return __awaiter(_this, void 0, void 0, function () {
            var updatedRow;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.floatingImportCorrectErrorsOpen == true)
                            return [2];
                        if (this.rowUpdating === row.id)
                            return [2];
                        return [4, this.importService.saveImportRowProperty(this.session.contextName, this.session.id, row.id, prop, n)];
                    case 1:
                        updatedRow = _a.sent();
                        this.updateExistingRow(updatedRow);
                        return [2];
                }
            });
        }); });
    };
    ImportStep4.prototype.updateExistingRow = function (updatedRow) {
        var _a;
        var _this = this;
        var existingRow = this.importedRows.find(function (x) { return x.id == updatedRow.id; });
        this.rowUpdating = existingRow.id;
        existingRow.isValid = updatedRow.isValid;
        existingRow.actions = updatedRow.actions;
        Object.keys(existingRow).filter(function (x) { return _this.technicalFields.indexOf(x) < 0; }).forEach(function (key) {
            existingRow[key] = updatedRow[key];
        });
        if (existingRow.serverErrors == null) {
            existingRow.serverErrors = [];
        }
        else {
            existingRow.serverErrors.splice(0);
        }
        (_a = existingRow.serverErrors).push.apply(_a, __spreadArray([], __read(updatedRow.serverErrors), false));
        this.constructMenuItems(existingRow);
        this.assignErrorProperties(existingRow);
        this.uiTableVM.filterChanged();
        this.nbOfError = this.importedRows.filter(function (x) { return x.isValid == false; }).length;
        ui_internal_1.UIInternal.nextTick(function () { return _this.rowUpdating = null; });
    };
    ImportStep4.prototype.confirm = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this;
                        return [4, this.importService.process(this.session.contextName, this.session.id)];
                    case 1:
                        _a.importResults = _b.sent();
                        this.newStep();
                        return [2];
                }
            });
        });
    };
    ImportStep4.prototype.constructMenuItems = function (row) {
        row.menu = this.getErrorRowContextMenu(row);
    };
    ImportStep4.prototype.assignErrorProperties = function (row) {
        var _a;
        Object.keys(row).filter(function (v) { return v.startsWith('errors'); }).forEach(function (errorPropKey) {
            row[errorPropKey] = null;
        });
        (_a = row.serverErrors) === null || _a === void 0 ? void 0 : _a.forEach(function (se) {
            row['errors' + se.propertyName] = [se.error];
        });
    };
    ImportStep4.prototype.getErrorRowContextMenu = function (currentThis) {
        var _this = this;
        var _a;
        var menu = [
            {
                group: "1",
                hiddenLabel: true,
                items: []
            }
        ];
        menu[0].items = (_a = currentThis.actions) === null || _a === void 0 ? void 0 : _a.map(function (a) {
            return {
                "label": _this.i18n.tr(a.labelTranslationKey),
                "icon": a.icon,
                handler: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.executeAction(currentThis, a)];
                        case 1: return [2, _a.sent()];
                    }
                }); }); }
            };
        });
        return menu;
    };
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Object)
    ], ImportStep4.prototype, "session", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Number)
    ], ImportStep4.prototype, "customParameters", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Object)
    ], ImportStep4.prototype, "errorTableView", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Object)
    ], ImportStep4.prototype, "newStep", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Object)
    ], ImportStep4.prototype, "cancelSession", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Boolean)
    ], ImportStep4.prototype, "hideCorrectedError", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Object)
    ], ImportStep4.prototype, "importResults", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Array)
    ], ImportStep4.prototype, "selectedErrors", void 0);
    __decorate([
        (0, aurelia_framework_1.computedFrom)('selectedErrors.length'),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], ImportStep4.prototype, "commonActions", null);
    ImportStep4 = __decorate([
        aurelia_framework_1.autoinject,
        (0, aurelia_framework_1.customElement)("import-step-4"),
        __metadata("design:paramtypes", [import_service_1.ImportService, global_loader_service_1.GlobalLoaderService, aurelia_i18n_1.I18N, aurelia_framework_1.BindingEngine, box_1.Box, aurelia_templating_resources_1.BindingSignaler])
    ], ImportStep4);
    return ImportStep4;
}());

//# sourceMappingURL=import-step-4.js.map
