"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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.BaseRelationFilter = void 0;
var aurelia_framework_1 = require("aurelia-framework");
var base_filter_1 = __importDefault(require("./base-filter"));
var service_base_1 = require("../../data/service-base");
var diacritic_regex_1 = require("diacritic-regex");
var MAX_SET_MODEL_RETRIES = 50;
var BaseRelationFilter = exports.BaseRelationFilter = (function (_super) {
    __extends(BaseRelationFilter, _super);
    function BaseRelationFilter() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.filterValuesSelected = [];
        _this.selectedIds = [];
        _this.displayEmptyFields = false;
        _this.selectedIdInternalChange = false;
        _this.currentSetModelRetries = 0;
        _this.ignoreChanges = false;
        return _this;
    }
    ;
    BaseRelationFilter.prototype.init = function (params) {
        this.filterChangedCallback = params.filterChangedCallback;
        _super.prototype.init.call(this, params);
        if (params.customdFieldPath != null) {
            this.fieldPath = params.customdFieldPath;
        }
        else {
            this.fieldPath = params.column.getColDef().field.split('.');
            this.fieldPath.splice(0, 1);
        }
        this.firstTime = false;
        this.loadValues();
    };
    BaseRelationFilter.prototype.valueSearchChanged = function (newVal, oldVal) {
        if (newVal != oldVal) {
            var regExp_1 = new RegExp((0, diacritic_regex_1.toRegex)({ flags: 'imu' })(newVal.trim().replace(/\/|\\/g, '')), 'imu');
            this.filterValues.forEach(function (filterValue) {
                var result = regExp_1.exec(filterValue.name.trim());
                filterValue.hide = !((result === null || result === void 0 ? void 0 : result.length) > 0);
            });
        }
    };
    BaseRelationFilter.prototype.isFilterActive = function () {
        var _a;
        return ((_a = this.filterValues) === null || _a === void 0 ? void 0 : _a.some(function (x) { return x.selected; })) || this.displayEmptyFields;
    };
    BaseRelationFilter.prototype.getModel = function () {
        return this.isFilterActive() ? {
            filterType: this.filterType, filter: this.filterValues, relationIdFieldName: this.relationIdFieldName
        } : null;
    };
    BaseRelationFilter.prototype.resetFilter = function () {
        var _a;
        (_a = this.filterValues) === null || _a === void 0 ? void 0 : _a.forEach(function (filterValue) { return filterValue.selected = false; });
        this.displayEmptyFields = false;
    };
    BaseRelationFilter.prototype.removeFilterValue = function (filterValue) {
        filterValue.selected = false;
    };
    BaseRelationFilter.prototype.setupContentGui = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, ''];
            });
        });
    };
    BaseRelationFilter.prototype.loadValues = function () {
        return __awaiter(this, void 0, void 0, function () {
            var oldFilterValues;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.isDestroyed()) {
                            return [2];
                        }
                        this.dispose();
                        oldFilterValues = this.filterValues;
                        return [4, this.getValues()];
                    case 1:
                        _a.sent();
                        if (oldFilterValues && oldFilterValues.length > 0) {
                            oldFilterValues.forEach(function (oldFilterValue) {
                                if (_this.filterValues && _this.filterValues.some(function (x) { return x.name == oldFilterValue.name; })) {
                                    _this.filterValues.find(function (x) { return x.name == oldFilterValue.name; }).selected = oldFilterValue.selected;
                                }
                            });
                        }
                        return [2];
                }
            });
        });
    };
    BaseRelationFilter.prototype.getValues = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        this.filterValues = new Array();
                        this.dispose();
                        _a = this;
                        if (!(this.service != null)) return [3, 2];
                        return [4, this.service.getEntities(this.service.gridDataSource.predicates, this.service.gridDataSource.expands, __assign(__assign({}, this.service.gridDataSource.queryParameters), { $inlinecount: 'allpages' }))];
                    case 1:
                        _b = _c.sent();
                        return [3, 3];
                    case 2:
                        _b = [];
                        _c.label = 3;
                    case 3:
                        _a.originalValues = _b;
                        this.setFilterValues(this.originalValues);
                        this.applyObservers();
                        return [2];
                }
            });
        });
    };
    BaseRelationFilter.prototype.setFilterValues = function (values) {
        var _this = this;
        this.ignoreChanges = true;
        this.filterValues.splice(0);
        values.forEach(function (value) {
            var obj = _this.filterValues.find(function (x) { return x.id == value["id"]; });
            if (obj == null) {
                obj = { id: value["id"], name: _this.getFieldValue(value), selected: false, hide: false };
                _this.filterValues.push(obj);
            }
        });
        this.filterValues.sortBy("name");
        this.ignoreChanges = false;
    };
    BaseRelationFilter.prototype.applyObservers = function () {
        var _this = this;
        var _a;
        this.dispose();
        (_a = this.filterValues) === null || _a === void 0 ? void 0 : _a.forEach(function (obj) {
            return _this.disposables.push(_this.bindingEngine.propertyObserver(obj, 'selected').subscribe(_this.filterValuesChanged.bind(_this)));
        });
        this.selectedIdsObserver = this.bindingEngine.collectionObserver(this.selectedIds).subscribe(function (changeRecords) {
            if (!_this.selectedIdInternalChange) {
                if ((changeRecords === null || changeRecords === void 0 ? void 0 : changeRecords.length) > 0 && changeRecords[0].removed.length > 0) {
                    changeRecords[0].removed.forEach(function (id) {
                        var value = _this.filterValues.find(function (x) { return x.id == id; });
                        if (value != null) {
                            value.selected = false;
                        }
                    });
                }
                _this.selectedIds.forEach(function (id) {
                    var value = _this.filterValues.find(function (x) { return x.id == id; });
                    if (value != null) {
                        value.selected = true;
                    }
                });
            }
        });
        this.disposables.push(this.bindingEngine.propertyObserver(this, 'displayEmptyFields').subscribe(function (newValue, oldValue) { return _this.filterValuesChanged(newValue, oldValue); }));
    };
    BaseRelationFilter.prototype.detectAndSetRelationIdFieldName = function (params) {
        var _a;
        if (params.relationIdFieldName != null) {
            this.relationIdFieldName = params.relationIdFieldName;
        }
        else {
            console.warn("Grid column ".concat((_a = params.colDef) === null || _a === void 0 ? void 0 : _a.field, " - relationIdFieldName parameter is missing. You should use the relationIdFieldName parameter to specify the name of the field containing the id of the relation, for better performance."));
        }
    };
    BaseRelationFilter.prototype.getFieldValue = function (value) {
        var fieldValue = value;
        this.fieldPath.forEach(function (fieldName) {
            var newFieldValue = fieldValue[fieldName];
            if (newFieldValue != null) {
                fieldValue = newFieldValue;
            }
        });
        return fieldValue;
    };
    BaseRelationFilter.prototype.filterValuesChanged = function (newVal, oldVal) {
        if (newVal != oldVal && !this.firstTime && !this.ignoreChanges) {
            this.setSelectedValues();
            var instance = this.params.api.getFilterInstance(this.params.colDef.field);
            instance.setModel(Object.assign({ filterType: this.filterType, filter: this.filterValues }, this.extendFilterValuesChangesModel()));
        }
    };
    BaseRelationFilter.prototype.extendFilterValuesChangesModel = function () {
        return {};
    };
    BaseRelationFilter.prototype.setSelectedValues = function () {
        var _a, _b;
        var _this = this;
        this.selectedIdInternalChange = true;
        this.filterValuesSelected.splice(0);
        (_a = this.filterValuesSelected).push.apply(_a, __spreadArray([], __read(this.filterValues.filter(function (x) { return x.selected; })), false));
        this.selectedIds.splice(0);
        (_b = this.selectedIds).push.apply(_b, __spreadArray([], __read(this.filterValuesSelected.map(function (x) { return x.id; })), false));
        this.DROPDOWN_NAME = this.getModelAsString();
        this.taskQueue.queueMicroTask(function () { return _this.selectedIdInternalChange = false; });
    };
    BaseRelationFilter.prototype.setModel = function (model) {
        var _this = this;
        this.currentSetModelRetries++;
        if (this.currentSetModelRetries > MAX_SET_MODEL_RETRIES) {
            console.error("Grid column ".concat(this.fieldPath, " - Max retries reached, cannot set model. Filters and views may be out of order."));
            return;
        }
        if (this.originalValues == null) {
            console.warn("Grid column ".concat(this.fieldPath, " - OriginalValues not loaded, cannot reset filter. Current retry counter is ").concat(this.currentSetModelRetries, "/").concat(MAX_SET_MODEL_RETRIES, ". Try again in 200ms."));
            setTimeout(function () { return _this.setModel(model); }, 200);
        }
        else {
            this.currentSetModelRetries = 0;
            this.internalSetModel(model);
        }
    };
    BaseRelationFilter.prototype.internalSetModel = function (model) {
        var _this = this;
        var _a;
        if (model == null) {
            if (this.originalValues == null) {
                console.error("Original values are null, cannot reset filter");
            }
            if (this.isDestroyed()) {
                this.dispose();
                this.filterValues = [];
            }
            else {
                this.resetFilter();
            }
        }
        else if (model.filterType == this.filterType) {
            var filterCopy = JSON.parse(JSON.stringify(model.filter));
            this.dispose();
            this.ignoreChanges = true;
            (_a = this.filterValues) === null || _a === void 0 ? void 0 : _a.forEach(function (filterValue) { return filterValue.selected = false; });
            filterCopy.forEach(function (fromModelValue) {
                var id = fromModelValue.id;
                var filterValue = _this.filterValues.find(function (x) { return x.id == id; });
                if (filterValue != null) {
                    filterValue.selected = fromModelValue.selected;
                }
                else {
                    console.warn("Original value not found for id " + id);
                }
            });
            this.applyObservers();
            this.setModelHook(model);
            setTimeout(function () {
                _this.ignoreChanges = false;
            }, 0);
        }
        this.setSelectedValues();
        this.filterChangedCallback();
    };
    BaseRelationFilter.prototype.setModelHook = function (model) {
    };
    BaseRelationFilter.prototype.getValue = function () {
        return this.filterValuesSelected;
    };
    BaseRelationFilter.prototype.getModelAsString = function () {
        return '';
    };
    BaseRelationFilter.prototype.dispose = function () {
        var _a;
        _super.prototype.dispose.call(this);
        this.disposables.splice(0);
        (_a = this.selectedIdsObserver) === null || _a === void 0 ? void 0 : _a.dispose();
        this.selectedIdsObserver = null;
    };
    BaseRelationFilter.prototype.buildService = function (params) {
        if (params.service != null) {
            this.service = params.service;
        }
        else if (params.serviceName != null) {
            this.service = new service_base_1.ServiceBase(params.serviceName);
        }
        else if (params.colDef.floatingFilterComponentParams.service != null) {
            this.service = params.colDef.floatingFilterComponentParams.service;
        }
        else if (params.colDef.floatingFilterComponentParams.serviceName != null) {
            this.service = new service_base_1.ServiceBase(params.colDef.floatingFilterComponentParams.serviceName);
        }
        if (this.service == null && !this.config.agGridConfig.suppressMenu) {
            throw new Error("service or serviceName parameter is missing");
        }
    };
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", String)
    ], BaseRelationFilter.prototype, "valueSearch", void 0);
    return BaseRelationFilter;
}(base_filter_1.default));

//# sourceMappingURL=base-relation-filter.js.map
