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 { validateTrigger, ValidationController, ValidationRules } from 'aurelia-validation';
import { autoinject, bindable, BindingEngine, customElement } from 'aurelia-framework';
import { ImportService } from "../../service/import-service";
import Fuse from 'fuse.js';
import { CustomDatasource } from '../step4/import-step-4';
import { ImportDefaultValueType } from '../../../model/common-model';
export var ImportStep3 = (function () {
    function ImportStep3(importService, bindingEngine, validationController) {
        this.importService = importService;
        this.bindingEngine = bindingEngine;
        this.validationController = validationController;
        this.ImportDefaultValueType = ImportDefaultValueType;
        this.separatorDisabled = true;
        this.fuseOption = {
            isCaseSensitive: false,
            minMatchCharLength: 3,
            keys: [
                "index",
                "columnName"
            ]
        };
    }
    ImportStep3.prototype.blurDefaultValue = function (mapping, uiSelect) {
        var _a;
        if (((_a = mapping.defaultValue) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            mapping.columnEndIndex = null;
        }
        this.validationController.validate({
            object: mapping,
            propertyName: "columnStartIndex"
        });
        uiSelect.au.controller.viewModel.select2Instance.trigger('selection:update', { data: mapping });
    };
    ImportStep3.prototype.blurCloseUiSelect = function (uiSelect) {
        uiSelect.au.controller.viewModel.close();
    };
    ImportStep3.prototype.bind = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, _b, isFirstTime, requiredCols;
            var _this = this;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        this.listService = new CustomDatasource(this.session, this.importService);
                        this.random = Date.now();
                        _a = this;
                        return [4, this.importService.getHeaderLabel(this.session.id)];
                    case 1:
                        _a.columns = _c.sent();
                        this.fuse = new Fuse(this.columns, this.fuseOption);
                        _b = this;
                        return [4, this.importService.getColumnMapping(this.session.id)];
                    case 2:
                        _b.columnsMapping = _c.sent();
                        isFirstTime = this.columnsMapping.filter(function (x) { return x.columnStartIndex == null; }).length == this.columnsMapping.length;
                        requiredCols = this.columnsMapping.filter(function (c) { var _a; return (_a = c.columnDefinition) === null || _a === void 0 ? void 0 : _a.isMandatory; });
                        ValidationRules.customRule('remote-config-validation', function (val, obj, args) { return __awaiter(_this, void 0, void 0, function () {
                            var result, valResults;
                            var _this = this;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        this.validationController.errors.splice(0);
                                        this.validationController.reset();
                                        result = true;
                                        return [4, this.importService.validateConfig(this.session.contextName, this.session.id, this.columnsMapping, this.session.config)];
                                    case 1:
                                        valResults = _a.sent();
                                        if (valResults.isValid)
                                            return [2, true];
                                        valResults.errors.forEach(function (e) {
                                            var propertyName = e.fieldName.toLowerCase();
                                            if (propertyName.indexOf('.') > 0) {
                                                propertyName = propertyName.split('.')[0];
                                            }
                                            var map = _this.columnsMapping.find(function (cm) { return cm.columnDefinition.propertyName.toLowerCase() == propertyName; });
                                            if (map == null)
                                                return;
                                            if (map != obj) {
                                                _this.validationController.addError(e.error, map, 'columnStartIndex');
                                            }
                                            else {
                                                result = false;
                                            }
                                        });
                                        return [2, result];
                                }
                            });
                        }); }, "test");
                        this.columnsMapping.forEach(function (c) {
                            ValidationRules
                                .ensure(function (p) { return p.columnStartIndex; })
                                .satisfiesRule('remote-config-validation')
                                .on(c);
                        });
                        this.validationController.changeTrigger(validateTrigger.changeOrBlur);
                        this.columnsMapping.forEach(function (mapping) {
                            if (isFirstTime) {
                                var fuseResult = _this.fuse.search(mapping.columnDefinition.propertyName);
                                if (fuseResult.length > 0) {
                                    mapping.columnStartIndex = fuseResult[0].item.index;
                                }
                                else {
                                    mapping.columnDefinition.columnNames.forEach(function (column) {
                                        if (mapping.columnStartIndex == null) {
                                            var fuseColumnResult = _this.fuse.search(column);
                                            if (fuseColumnResult.length > 0) {
                                                mapping.columnStartIndex = fuseColumnResult[0].item.index;
                                            }
                                        }
                                    });
                                }
                            }
                        });
                        return [2];
                }
            });
        });
    };
    ImportStep3.prototype.confirm = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(((_a = this.validationController.errors) === null || _a === void 0 ? void 0 : _a.length) == 0)) return [3, 4];
                        return [4, this.importService.saveMapping(this.session.id, this.columnsMapping)];
                    case 1:
                        _b.sent();
                        if (!(this.session.config != null)) return [3, 3];
                        return [4, this.importService.saveConfig(this.session.contextName, this.session.id, this.session.config)];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3:
                        this.newStep();
                        return [3, 5];
                    case 4:
                        alert('error');
                        _b.label = 5;
                    case 5: return [2];
                }
            });
        });
    };
    ImportStep3.prototype.getTemplate = function (mapping) {
        if (mapping.columnStartIndex != null) {
            var startIndex = mapping.columnStartIndex == -1 ? (this.columns.length - 1) : mapping.columnStartIndex;
            if (mapping.columnEndIndex != null && mapping.columnEndIndex != "''") {
                return this.columns[startIndex].fullName + " - " + this.columns[mapping.columnEndIndex].fullName;
            }
            else {
                return this.columns[startIndex].fullName;
            }
        }
        else {
            return "";
        }
    };
    __decorate([
        bindable,
        __metadata("design:type", Object)
    ], ImportStep3.prototype, "session", void 0);
    __decorate([
        bindable,
        __metadata("design:type", Object)
    ], ImportStep3.prototype, "newStep", void 0);
    __decorate([
        bindable,
        __metadata("design:type", Object)
    ], ImportStep3.prototype, "cancelSession", void 0);
    __decorate([
        bindable,
        __metadata("design:type", Object)
    ], ImportStep3.prototype, "configView", void 0);
    ImportStep3 = __decorate([
        autoinject,
        customElement("import-step-3"),
        __metadata("design:paramtypes", [ImportService, BindingEngine, ValidationController])
    ], ImportStep3);
    return ImportStep3;
}());

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