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));
};
import { Container, TaskQueue } from 'aurelia-framework';
import { UserPreFilter } from './../../../model/common-model';
import { BindingEngine, observable } from "aurelia-binding";
import { Utils } from './../../../utils/utils';
var MAX_SET_MODEL_RETRIES = 50;
export var UserFilterHelper = (function () {
    function UserFilterHelper(service, firstTime, setInstanceModel, setDropdownName) {
        if (firstTime === void 0) { firstTime = true; }
        this.service = service;
        this.firstTime = firstTime;
        this.setInstanceModel = setInstanceModel;
        this.setDropdownName = setDropdownName;
        this.disposables = [];
        this.selectedIds = [];
        this.selectedIdInternalChange = false;
        this.userValuesSelected = [];
        this.currentSetModelRetries = 0;
        this.displayEmptyFields = false;
        this.isGettingUsers = false;
        this.bindingEngine = Container.instance.get(BindingEngine);
        this.taskQueue = Container.instance.get(TaskQueue);
        this.groupName = Math.random().toString();
        this.getUsers();
    }
    UserFilterHelper.prototype.resetFilter = function () {
        this.resetUserPreFilter();
        this.resetUserValues();
        this.displayEmptyFields = false;
    };
    UserFilterHelper.prototype.resetUserValues = function () {
        if (this.userValues != null && Array.isArray(this.userValues)) {
            this.userValues.forEach(function (userValue) {
                userValue.selected = false;
            });
        }
    };
    UserFilterHelper.prototype.isFilterActive = function () {
        if (this.selectedUserPreFilter != null || this.displayEmptyFields) {
            return true;
        }
        if (this.userValues != null && Array.isArray(this.userValues)) {
            return this.userValues.some(function (x) { return x.selected; });
        }
        return false;
    };
    UserFilterHelper.prototype.isGettingUsersChanged = function (newVal, oldVal) {
        if (newVal != oldVal && !this.isGettingUsers && this.setModelTemp != null) {
            this.setModelTemp();
        }
    };
    UserFilterHelper.prototype.setModel = function (model) {
        var _this = this;
        this.selectedUserPreFilter = model === null || model === void 0 ? void 0 : model.userPreFilter;
        if (this.isGettingUsers) {
            this.setModelTemp = function () { return _this.setModel(model); };
            return;
        }
        this.currentSetModelRetries++;
        if (this.currentSetModelRetries > MAX_SET_MODEL_RETRIES) {
            console.error("Grid column UserFilter - Max retries reached, cannot set model. Filters and views may be out of order.");
            return;
        }
        if (this.userValues == null) {
            console.warn("Grid column UserFilter - 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);
        }
    };
    UserFilterHelper.prototype.internalSetModel = function (model) {
        var _a, _b;
        var _this = this;
        if (model == null) {
            this.selectedUserPreFilter = null;
            this.userValues = new Array();
            this.userValuesSelected.splice(0);
            this.selectedIds.splice(0);
        }
        else if (model.filterType == 'user') {
            if (this.selectedUserPreFilter == null) {
                this.userValuesSelected.splice(0);
                this.selectedIds.splice(0);
                this.userValues.forEach(function (x) { return x.selected == false; });
                if (model.filter != null) {
                    var filterCopy = JSON.parse(JSON.stringify(model.filter));
                    filterCopy.forEach(function (x) {
                        var user = _this.userValues.find(function (u) { return u.id == x.id; });
                        if (user != null) {
                            user.selected = x.selected;
                        }
                    });
                }
                (_a = this.userValuesSelected).push.apply(_a, __spreadArray([], __read(this.userValues.filter(function (x) { return x.selected; })), false));
                (_b = this.selectedIds).push.apply(_b, __spreadArray([], __read(this.userValuesSelected.map(function (x) { return x.id; })), false));
            }
        }
        this.applyObservers();
    };
    UserFilterHelper.prototype.onOpenDropDown = function (oldUserValues) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, _b;
            var _this = this;
            return __generator(this, function (_c) {
                oldUserValues.forEach(function (oldUserValue) {
                    if (_this.userValues && _this.userValues.some(function (x) { return x.name == oldUserValue.name; })) {
                        _this.userValues.find(function (x) { return x.name == oldUserValue.name; }).selected = oldUserValue.selected;
                    }
                });
                this.userValuesSelected.splice(0);
                (_a = this.userValuesSelected).push.apply(_a, __spreadArray([], __read(this.userValues.filter(function (x) { return x.selected; })), false));
                this.selectedIds.splice(0);
                (_b = this.selectedIds).push.apply(_b, __spreadArray([], __read(this.userValuesSelected.map(function (x) { return x.id; })), false));
                return [2];
            });
        });
    };
    UserFilterHelper.prototype.setupContentGui = function () {
        return "\n      <div class=\"floating-filter__body__user\">\n        <div class=\"floating-filter__body__search\">\n            <ui-field t=\"[label]common:grid.searchShort\">\n                <ui-input type=\"text\" value.bind=\"filterHelper.userSearch & debounce:500\" clear>\n                    <ui-input-addon icon=\"digi-search\"></ui-input-addon>\n                </ui-input>\n            </ui-field>\n            <div class=\"ui-check__wrapper\" if.bind=\"showEmptyFieldsCheckbox\">\n                <ui-checkbox checked.bind=\"filterHelper.displayEmptyFields\">${ 'grid.displayEmptyFields' | t }</ui-checkbox>\n            </div>\n        </div>\n\n        <div class=\"floating-filter__body__user__radio\">\n          <div>\n            <ui-radio name=\"".concat(this.groupName, "\" model.one-time=\"1\" checked.bind=\"filterHelper.selectedUserPreFilter\"><span t=\"[html]common:grid.me\"></span></ui-radio>\n          </div>\n          <div>\n            <ui-radio name=\"").concat(this.groupName, "\" model.one-time=\"2\" checked.bind=\"filterHelper.selectedUserPreFilter\"><span t=\"[html]common:grid.notMe\"></span></ui-radio>\n          </div>\n        </div>       \n\n        <div class=\"floating-filter__body__user__list\">\n          <div repeat.for=\"userValue of filterHelper.userValues\" show.bind=\"!userValue.hide\" class=\"floating-filter__body__user__list__elem\">\n            <ui-checkbox checked.bind=\"userValue.selected\" title.bind=\"userValue.name\">\n              ${userValue.name}\n            </ui-checkbox>\n          </div>\n        </div>\n        \n      </div>");
    };
    UserFilterHelper.prototype.getValue = function () {
        if (this.userValuesSelected.length > 0) {
            return this.userValuesSelected;
        }
        else {
            return this.selectedUserPreFilter;
        }
    };
    UserFilterHelper.prototype.setupContentGuiSideFilter = function () {
        return "\n        <div class=\"col s12 m12 l12\">\n            <ui-field label.bind=\"params.colDef.headerName\">\n                <ui-select multiple t=\"[placeholder]general.chooseAnOption\" value.bind=\"filterHelper.selectedIds\"\n                    data-source.bind=\"filterHelper.service.gridDataSource\" options-text=\"fullName\"\n                    filter-properties.bind=\"['fullName']\" options-value=\"id\">\n                    <option></option>\n                    <option repeat.for=\"value of filterHelper.userValuesSelected\" value.bind=\"value.id\" selected.bind=\"true\">\n                    ${value.name}</option>\n                    <ui-select-header-template>\n                        <div class=\"ui-check__wrapper\" if.bind=\"showEmptyFieldsCheckbox\">\n                            <ui-checkbox checked.bind=\"filterHelper.displayEmptyFields\">${ 'grid.displayEmptyFields' | t }</ui-checkbox>\n                        </div>\n                    </ui-select-header-template>\n                </ui-select>\n            </ui-field>\n        </div>";
    };
    UserFilterHelper.prototype.getUsers = function (applyObservers) {
        if (applyObservers === void 0) { applyObservers = true; }
        return __awaiter(this, void 0, void 0, function () {
            var users;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.isGettingUsers = true;
                        return [4, this.service.getEntities(this.service.gridDataSource.predicates, this.service.gridDataSource.expands, this.service.gridDataSource.queryParameters)];
                    case 1:
                        users = _a.sent();
                        ;
                        this.userValues = users
                            .filter(function (u, index) { return !Utils.isNullOrEmpty(u.fullName) && users.indexOf(u) === index; })
                            .map(function (u) {
                            return { id: u.id, name: u.fullName, selected: false, hide: false };
                        });
                        if (applyObservers) {
                            this.applyObservers();
                        }
                        this.userValues.sortBy("name");
                        this.isGettingUsers = false;
                        return [2];
                }
            });
        });
    };
    UserFilterHelper.prototype.applyObservers = function () {
        var _this = this;
        var _a;
        this.dispose();
        this.disposableUserValues = new Array();
        (_a = this.userValues) === null || _a === void 0 ? void 0 : _a.forEach(function (obj) {
            return _this.disposableUserValues.push(_this.bindingEngine.propertyObserver(obj, 'selected').subscribe(_this.userValuesChanged.bind(_this)));
        });
        this.selectedIdsObserver = this.bindingEngine.collectionObserver(this.selectedIds).subscribe(function (changeRecords) { return __awaiter(_this, void 0, void 0, function () {
            var _this = this;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!this.selectedIdInternalChange) return [3, 3];
                        if (!(this.userValues == null || this.userValues.length == 0)) return [3, 2];
                        return [4, this.getUsers(false)];
                    case 1:
                        _b.sent();
                        (_a = this.userValues) === null || _a === void 0 ? void 0 : _a.forEach(function (obj) {
                            return _this.disposableUserValues.push(_this.bindingEngine.propertyObserver(obj, 'selected').subscribe(_this.userValuesChanged.bind(_this)));
                        });
                        _b.label = 2;
                    case 2:
                        if ((changeRecords === null || changeRecords === void 0 ? void 0 : changeRecords.length) > 0 && changeRecords[0].removed.length > 0) {
                            changeRecords[0].removed.forEach(function (id) {
                                var _a;
                                var value = (_a = _this.userValues) === null || _a === void 0 ? void 0 : _a.find(function (x) { return x.id == id; });
                                if (value != null) {
                                    value.selected = false;
                                }
                            });
                        }
                        this.selectedIds.forEach(function (id) {
                            var _a;
                            var value = (_a = _this.userValues) === null || _a === void 0 ? void 0 : _a.find(function (x) { return x.id == id; });
                            if (value != null) {
                                value.selected = true;
                            }
                        });
                        _b.label = 3;
                    case 3: return [2];
                }
            });
        }); });
        this.disposables.push(this.bindingEngine.propertyObserver(this, 'displayEmptyFields').subscribe(this.userValuesChanged.bind(this)));
    };
    UserFilterHelper.prototype.removeDisposables = function (all) {
        if (all && this.disposableUserValues) {
            this.disposableUserValues.forEach(function (x) { return x.dispose(); });
        }
        this.dispose();
    };
    UserFilterHelper.prototype.dispose = function () {
        var _a, _b;
        (_a = this.disposableUserValues) === null || _a === void 0 ? void 0 : _a.forEach(function (x) { return x.dispose(); });
        (_b = this.selectedIdsObserver) === null || _b === void 0 ? void 0 : _b.dispose();
    };
    UserFilterHelper.prototype.setFirstTime = function (firstTime) {
        this.firstTime = firstTime;
    };
    UserFilterHelper.prototype.userSearchChanged = function (newVal, oldVal) {
        if (newVal != oldVal && !this.firstTime) {
            this.userValues.forEach(function (userValue) {
                userValue.hide = !(userValue.name.toUpperCase().includes(newVal.toUpperCase()));
            });
        }
    };
    UserFilterHelper.prototype.userValuesChanged = function (newVal, oldVal) {
        var _a, _b;
        var _this = this;
        if (this.ignoreUserValuesChanged)
            return;
        if (newVal != oldVal) {
            this.selectedIdInternalChange = true;
            this.ignoreSelectedUserPreFilterChanged = true;
            this.userValuesSelected.splice(0);
            (_a = this.userValuesSelected).push.apply(_a, __spreadArray([], __read(this.userValues.filter(function (x) { return x.selected; })), false));
            this.selectedIds.splice(0);
            (_b = this.selectedIds).push.apply(_b, __spreadArray([], __read(this.userValuesSelected.map(function (x) { return x.id; })), false));
            this.setDropdownName();
            this.setInstanceModel({ filterType: 'user', filter: this.userValues, displayEmptyFields: this.displayEmptyFields });
            this.resetUserPreFilter();
            this.taskQueue.queueMicroTask(function () { return _this.ignoreSelectedUserPreFilterChanged = false; });
            this.selectedIdInternalChange = false;
        }
    };
    UserFilterHelper.prototype.selectedUserPreFilterChanged = function (newVal, oldVal) {
        var _this = this;
        if (this.ignoreSelectedUserPreFilterChanged)
            return;
        if (newVal != oldVal && !this.firstTime) {
            this.ignoreUserValuesChanged = true;
            var model = { filterType: 'user', displayEmptyFields: this.displayEmptyFields };
            if (this.selectedUserPreFilter == UserPreFilter.Me) {
                this.setInstanceModel(Object.assign(model, { type: 'equals', userPreFilter: this.selectedUserPreFilter }));
                this.resetUserValues();
            }
            else if (this.selectedUserPreFilter == UserPreFilter.NotMe) {
                this.setInstanceModel(Object.assign(model, { type: 'notEqual', userPreFilter: this.selectedUserPreFilter }));
                this.resetUserValues();
            }
            else {
                this.setInstanceModel(Object.assign(model, { filter: null }));
            }
            this.taskQueue.queueMicroTask(function () { return _this.ignoreUserValuesChanged = false; });
        }
    };
    UserFilterHelper.prototype.resetUserPreFilter = function () {
        this.selectedUserPreFilter = null;
    };
    __decorate([
        observable,
        __metadata("design:type", String)
    ], UserFilterHelper.prototype, "userSearch", void 0);
    __decorate([
        observable,
        __metadata("design:type", Number)
    ], UserFilterHelper.prototype, "selectedUserPreFilter", void 0);
    __decorate([
        observable,
        __metadata("design:type", Boolean)
    ], UserFilterHelper.prototype, "isGettingUsers", void 0);
    __decorate([
        observable,
        __metadata("design:type", Function)
    ], UserFilterHelper.prototype, "setModelTemp", void 0);
    return UserFilterHelper;
}());

//# sourceMappingURL=user-filter-helper.js.map
