(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@c8y/ngx-components/sub-assets'), require('lodash-es'), require('@ngx-translate/core'), require('@c8y/client'), require('@c8y/ngx-components'), require('@c8y/client'), require('@c8y/ngx-components/assets-navigator'), require('@c8y/client'), require('@c8y/client'), require('@angular/router'), require('@c8y/client'), require('@c8y/ngx-components/device-grid'), require('rxjs'), require('rxjs/operators'), require('ngx-bootstrap/dropdown'), require('ngx-bootstrap/modal')) :
    typeof define === 'function' && define.amd ? define('@c8y/ngx-components/search', ['exports', '@angular/core', '@c8y/ngx-components/sub-assets', 'lodash-es', '@ngx-translate/core', '@c8y/client', '@c8y/ngx-components', '@c8y/client', '@c8y/ngx-components/assets-navigator', '@c8y/client', '@c8y/client', '@angular/router', '@c8y/client', '@c8y/ngx-components/device-grid', 'rxjs', 'rxjs/operators', 'ngx-bootstrap/dropdown', 'ngx-bootstrap/modal'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.c8y = global.c8y || {}, global.c8y["ngx-components"] = global.c8y["ngx-components"] || {}, global.c8y["ngx-components"].search = {}), global.ng.core, global.c8y["ngx-components"]["sub-assets"], global.lodashEs, global.i1, global.i2, global.c8y["ngx-components"], global.i4, global.i5, global.i6, global.i7, global.ng.router, global.client, global.c8y["ngx-components"]["device-grid"], global.rxjs, global.rxjs.operators, global.dropdown, global.modal));
})(this, (function (exports, i0, subAssets, lodashEs, i1, i2, i3, i4, i5, i6, i7, router, client, deviceGrid, rxjs, operators, dropdown, modal) { 'use strict';

    function _interopNamespace(e) {
        if (e && e.__esModule) return e;
        var n = Object.create(null);
        if (e) {
            Object.keys(e).forEach(function (k) {
                if (k !== 'default') {
                    var d = Object.getOwnPropertyDescriptor(e, k);
                    Object.defineProperty(n, k, d.get ? d : {
                        enumerable: true,
                        get: function () { return e[k]; }
                    });
                }
            });
        }
        n["default"] = e;
        return Object.freeze(n);
    }

    var i0__namespace = /*#__PURE__*/_interopNamespace(i0);
    var i1__namespace = /*#__PURE__*/_interopNamespace(i1);
    var i2__namespace = /*#__PURE__*/_interopNamespace(i2);
    var i3__namespace = /*#__PURE__*/_interopNamespace(i3);
    var i4__namespace = /*#__PURE__*/_interopNamespace(i4);
    var i5__namespace = /*#__PURE__*/_interopNamespace(i5);
    var i6__namespace = /*#__PURE__*/_interopNamespace(i6);
    var i7__namespace = /*#__PURE__*/_interopNamespace(i7);

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise */
    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);
    };
    function __extends(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 = function () {
        __assign = Object.assign || function __assign(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);
    };
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    function __decorate(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;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    function __awaiter(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());
        });
    }
    function __generator(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 (_)
                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 __createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                __createBinding(o, m, p);
    }
    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m)
            return m.call(o);
        if (o && typeof o.length === "number")
            return {
                next: function () {
                    if (o && i >= o.length)
                        o = void 0;
                    return { value: o && o[i++], done: !o };
                }
            };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(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;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    function __spreadArray(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));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) { if (g[n])
            i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
        function resume(n, v) { try {
            step(g[n](v));
        }
        catch (e) {
            settle(q[0][3], e);
        } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length)
            resume(q[0][0], q[0][1]); }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }

    var AssetSearchService = /** @class */ (function (_super) {
        __extends(AssetSearchService, _super);
        function AssetSearchService() {
            var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
            _this.GRID_CONFIG_STORAGE_KEY = 'search-grid-config';
            _this.DEFAULT_PAGE_SIZE = 50;
            _this.FRAGMENTS_FOR_NO_DEVICE = [
                'c8y_Dashboard',
                'c8y_Report',
                'c8y_Kpi',
                'c8y_ExportConfiguration',
                'c8y_IsBinary',
                'c8y_NoDevice',
                'c8y_IsDeviceGroup',
                'c8y_Group',
                'com_cumulocity_model_smartrest_SmartRestTemplate',
                'com_cumulocity_model_devicesimulator_SensorTemplate',
                '_attachments',
                'c8y_IsDeviceType',
                'c8y_objectmapping_ObjectMapping'
            ];
            _this.TYPES_FOR_NO_DEVICE = [
                'c8y_ConfigurationDump',
                'c8y_Firmware',
                'c8y_SmartRule',
                'c8y_Software',
                'impact_object_mapping',
                'c8y_UserPreference',
                'c8y_TenantPolicy',
                'c8y_PrivateSmartRule',
                'c8y_SmartRest2Template',
                'c8y_JsonSchema',
                'c8y_DeviceShellTemplate',
                'c8y_DemoStatus',
                'c8y_DataBroker',
                'c8y_Application_',
                'brandingVariables',
                'c8y_DeviceSimulator',
                'c8y_CertificateMetadata',
                'lwm2m_post_registration',
                'c8y_microservice_manifest_',
                'c8y_CepAgent'
            ];
            _this.DEVICE_FRAGMENT_TYPE = 'c8y_IsDevice';
            return _this;
        }
        /**
         * Will return only valid assets (groups and devices) and filter out
         * none useful inventories (e.g. c8y_JsonSchema).
         * @param data All managed objects that should be filtered.
         */
        AssetSearchService.prototype.filterOnlyAssets = function (data) {
            var _this = this;
            return data.filter(function (mo) { return mo.c8y_IsDeviceGroup || _this.isAnyDevice(mo); });
        };
        AssetSearchService.prototype.buildCombinedRootQueryFilter = function (columns, pagination) {
            var rootQuery = {
                __filter: {
                    __and: { __not: { __has: "c8y_IsBinary" } }
                }
            };
            var userQuery = this.getQueryObj(columns, pagination);
            var queryPart = this.queriesUtil.addOrderbys(rootQuery, userQuery.__orderby, 'append');
            var fullQuery = this.queriesUtil.addAndFilter(queryPart, userQuery.__filter);
            return this.queriesUtil.buildQuery(fullQuery);
        };
        /**
         * Returns the full-text search results.
         *
         * @param term The search term.
         * @param pagination The currently used pagination.
         */
        AssetSearchService.prototype.search = function (term, pagination) {
            if (pagination === void 0) { pagination = { currentPage: 1, pageSize: this.DEFAULT_PAGE_SIZE }; }
            return this.inventoryService.list({
                text: term,
                withTotalPages: true,
                pageSize: pagination.pageSize,
                withChildren: false,
                currentPage: pagination.currentPage || 1
            });
        };
        AssetSearchService.prototype.isRootDevice = function (mo) {
            return !!mo[this.DEVICE_FRAGMENT_TYPE];
        };
        AssetSearchService.prototype.isAnyDevice = function (mo) {
            var isDevice = this.isRootDevice(mo) || !this.hasFragmentOrTypeFromBlacklist(mo);
            return isDevice;
        };
        AssetSearchService.prototype.hasFragmentOrTypeFromBlacklist = function (mo) {
            return this.hasTypeFromBlacklist(mo) || this.hasFragmentFromBlacklist(mo);
        };
        AssetSearchService.prototype.hasTypeFromBlacklist = function (mo) {
            var moType = lodashEs.get(mo, 'type', '');
            return lodashEs.some(this.TYPES_FOR_NO_DEVICE, function (type) { return moType.includes(type); });
        };
        AssetSearchService.prototype.hasFragmentFromBlacklist = function (mo) {
            return lodashEs.find(this.FRAGMENTS_FOR_NO_DEVICE, function (f) { return !lodashEs.isUndefined(mo[f]); });
        };
        return AssetSearchService;
    }(subAssets.SubAssetsService));
    AssetSearchService.ɵprov = i0__namespace.ɵɵdefineInjectable({ factory: function AssetSearchService_Factory() { return new AssetSearchService(i0__namespace.ɵɵinject(i1__namespace.TranslateService), i0__namespace.ɵɵinject(i2__namespace.InventoryService), i0__namespace.ɵɵinject(i3__namespace.AppStateService), i0__namespace.ɵɵinject(i4__namespace.UserService), i0__namespace.ɵɵinject(i5__namespace.AssetNodeService), i0__namespace.ɵɵinject(i5__namespace.DeviceGroupService), i0__namespace.ɵɵinject(i6__namespace.SmartGroupsService), i0__namespace.ɵɵinject(i7__namespace.SmartRulesService), i0__namespace.ɵɵinject(i3__namespace.AlertService), i0__namespace.ɵɵinject(i3__namespace.Permissions), i0__namespace.ɵɵinject(i3__namespace.ModalService)); }, token: AssetSearchService, providedIn: "root" });
    AssetSearchService.decorators = [
        { type: i0.Injectable, args: [{
                    providedIn: 'root'
                },] }
    ];

    var SearchBoxComponent = /** @class */ (function () {
        function SearchBoxComponent(router, inventory, deviceGridService, searchService) {
            var _this = this;
            this.router = router;
            this.inventory = inventory;
            this.deviceGridService = deviceGridService;
            this.searchService = searchService;
            this.term = '';
            this.filterPipe = rxjs.pipe(operators.map(function (data) {
                return _this.searchService.filterOnlyAssets(data);
            }));
            this.recentSearchResults = [];
            this.isLoading = false;
            this.noMatch = false;
            this.RECENT_SEARCH_STORAGE_KEY = 'recent_search_view';
            this.MAX_RECENT_SEARCH_RESULTS = 5;
            this.DEFAULT_FILTER = {
                withTotalPages: true,
                pageSize: 5,
                withChildren: false
            };
            this.KEYCODE_ENTER = 13;
            this.KEYCODE_ESC = 27;
        }
        SearchBoxComponent.prototype.ngOnInit = function () {
            return __awaiter(this, void 0, void 0, function () {
                var recentSearchIds, data;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            recentSearchIds = JSON.parse(localStorage.getItem(this.RECENT_SEARCH_STORAGE_KEY));
                            if (!(recentSearchIds && recentSearchIds.length > 0)) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.inventory.list({ ids: recentSearchIds.join(',') })];
                        case 1:
                            data = (_a.sent()).data;
                            this.recentSearchResults = data;
                            this.recentlyRegisteredResults$ = rxjs.defer(function () { return _this.inventory.list(Object.assign({ q: '$orderby=creationTime desc' }, _this.DEFAULT_FILTER)); });
                            _a.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            });
        };
        SearchBoxComponent.prototype.onOpenChange = function (isOpen) {
            var _this = this;
            if (isOpen) {
                // needs to request an animation frame as
                // otherwise the typeahead is undefined
                requestAnimationFrame(function () {
                    _this.subscribeOnSearch();
                    _this.typeahead.dropdown.show();
                    _this.typeahead.searchControl.nativeElement.focus();
                });
            }
        };
        SearchBoxComponent.prototype.open = function (event, mo) {
            event.stopPropagation();
            var isAlreadyRecent = this.recentSearchResults.find(function (_a) {
                var id = _a.id;
                return id === mo.id;
            });
            if (!isAlreadyRecent) {
                this.recentSearchResults.unshift(mo);
                this.recentSearchResults = this.recentSearchResults.slice(0, this.MAX_RECENT_SEARCH_RESULTS);
            }
            var recentSearchIds = this.recentSearchResults.map(function (_a) {
                var id = _a.id;
                return id;
            });
            localStorage.setItem(this.RECENT_SEARCH_STORAGE_KEY, JSON.stringify(recentSearchIds));
            this.router.navigateByUrl(this.deviceGridService.getHref(mo, '/'));
            this.dropdown.hide();
        };
        SearchBoxComponent.prototype.reset = function () {
            this.typeahead.onSearch.emit('');
            this.selected = undefined;
            this.typeahead.searchControl.nativeElement.focus();
        };
        SearchBoxComponent.prototype.keyDown = function (event) {
            var keyCode = event.keyCode;
            if (keyCode === this.KEYCODE_ENTER) {
                // enter hit can be faster then typeahead debounce,
                // therefore we take the term from the DOM element
                // itself:
                var searchTerm = event.target.value;
                this.navigate(['/assetsearch'], { queryParams: { search: searchTerm } });
                this.dropdown.hide();
            }
            else if (keyCode === this.KEYCODE_ESC) {
                if (this.term === '') {
                    this.dropdown.hide();
                }
                this.reset();
            }
        };
        SearchBoxComponent.prototype.filter = function (on) {
            this.navigate(['/assetsearch'], { queryParams: { filter: on } });
            this.dropdown.hide();
        };
        SearchBoxComponent.prototype.openSearch = function () {
            this.router.navigateByUrl('/assetsearch');
            this.dropdown.hide();
        };
        SearchBoxComponent.prototype.subscribeOnSearch = function () {
            var _this = this;
            if (!this.results$) {
                this.results$ = this.typeahead.onSearch.pipe(operators.tap(function (term) { return _this.onTypingStarted(term); }), operators.switchMap(function (term) { return _this.mergeRequest(term); }));
            }
        };
        SearchBoxComponent.prototype.navigate = function (commands, extras) {
            var _this = this;
            this.router
                .navigateByUrl('/', { skipLocationChange: true })
                .then(function () { return _this.router.navigate(commands, extras); });
        };
        SearchBoxComponent.prototype.mergeRequest = function (term) {
            var _this = this;
            return rxjs.merge(rxjs.of({ data: [] }), this.queryInventoryService(term).pipe(operators.tap(function (_a) {
                var data = _a.data, paging = _a.paging;
                return _this.onLoadingDone(data, paging);
            })));
        };
        SearchBoxComponent.prototype.queryInventoryService = function (term) {
            var _this = this;
            if (term) {
                return rxjs.defer(function () { return _this.searchService.search(term); });
            }
            return rxjs.empty();
        };
        SearchBoxComponent.prototype.onLoadingDone = function (data, paging) {
            this.isLoading = false;
            this.noMatch =
                paging && paging.nextPage === null && this.searchService.filterOnlyAssets(data).length === 0;
        };
        SearchBoxComponent.prototype.onTypingStarted = function (term) {
            this.noMatch = false;
            this.term = term;
            this.isLoading = term.length > 0;
        };
        return SearchBoxComponent;
    }());
    SearchBoxComponent.decorators = [
        { type: i0.Component, args: [{
                    selector: 'c8y-search-box',
                    template: "<div\n  class=\"dropdown\"\n  dropdown\n  #dropdown=\"bs-dropdown\"\n  [insideClick]=\"true\"\n  (isOpenChange)=\"onOpenChange($event)\"\n>\n  <button\n    class=\"main-header-button dropdown-toggle c8y-dropdown\"\n    dropdownToggle\n    type=\"button\"\n    title=\"Search\"\n    aria-controls=\"searchDropdown\"\n  >\n    <i c8yIcon=\"search\" class=\"icon-2x\"></i>\n  </button>\n\n  <div\n    id=\"searchDropdown\"\n    *dropdownMenu\n    class=\"search-header-menu dropdown-menu dropdown-menu-center\"\n  >\n    <form novalidate #searchForm=\"ngForm\" class=\"c8y-search-form\">\n      <c8y-typeahead\n        [(ngModel)]=\"selected\"\n        placeholder=\"{{ 'Search for groups or assets\u2026' | translate }}\"\n        (keydown)=\"keyDown($event)\"\n        (onIconClick)=\"reset()\"\n        [icon]=\"term ? 'times' : 'search'\"\n        [allowFreeEntries]=\"false\"\n        name=\"selected\"\n      >\n        <!-- filter buttons -->\n        <c8y-li *ngIf=\"term.length !== 0\" class=\"p-l-16 p-r-16\">\n          <div class=\"flex-row\">\n            <p class=\"m-r-4 text-muted\">\n              <em translate>Searching by exact match. Click for other search options:</em>\n            </p>\n            <div class=\"btn-group btn-group-sm\">\n              <button\n                class=\"btn btn-default\"\n                title=\"{{ 'Starts with' | translate }}\"\n                (click)=\"filter(term + '*')\"\n              >\n                {{ 'Starts with' | translate }}\n              </button>\n              <button\n                class=\"btn btn-default\"\n                title=\"{{ 'Contains' | translate }}\"\n                (click)=\"filter('*' + term + '*')\"\n              >\n                {{ 'Contains' | translate }}\n              </button>\n              <button\n                class=\"btn btn-default\"\n                title=\"{{ 'Ends with' | translate }}\"\n                (click)=\"filter('*' + term)\"\n              >\n                {{ 'Ends with' | translate }}\n              </button>\n            </div>\n          </div>\n        </c8y-li>\n\n        <!-- Recent search -->\n        <c8y-li\n          *ngIf=\"term.length === 0 && recentSearchResults.length > 0\"\n          [selectable]=\"false\"\n          class=\"p-l-24 p-r-24\"\n        >\n          <div class=\"legend form-block\">\n            <span translate>Recent search results</span>\n          </div>\n        </c8y-li>\n        <c8y-li\n          *ngFor=\"let result of term.length === 0 ? recentSearchResults : []\"\n          class=\"c8y-list__item--link m-l-16 m-r-16\"\n          (click)=\"open($event, result)\"\n        >\n          <c8y-li-icon>\n            <device-status [mo]=\"result\" *ngIf=\"!result.c8y_IsDeviceGroup\"></device-status>\n            <i\n              [c8yIcon]=\"'c8y-group-open'\"\n              class=\"c8y-icon-duocolor\"\n              *ngIf=\"result.c8y_IsDeviceGroup\"\n            ></i>\n          </c8y-li-icon>\n          {{ result.name || '--' }}\n        </c8y-li>\n\n        <!-- Recently registered devices -->\n        <c8y-li\n          *ngIf=\"term.length === 0 && (recentlyRegisteredResults$ | async)?.data?.length > 0\"\n          class=\"p-l-24 p-r-24\"\n          [selectable]=\"false\"\n        >\n          <div class=\"legend form-block\">\n            <span translate>Recently registered devices</span>\n          </div>\n        </c8y-li>\n        <c8y-li\n          *c8yFor=\"\n            let result of term.length === 0 ? recentlyRegisteredResults$ : { data: [] };\n            loadMore: 'none';\n            pipe: filterPipe\n          \"\n          class=\"c8y-list__item--link m-l-16 m-r-16\"\n          (click)=\"open($event, result)\"\n        >\n          <c8y-li-icon>\n            <device-status [mo]=\"result\" *ngIf=\"!result.c8y_IsDeviceGroup\"></device-status>\n            <i\n              [c8yIcon]=\"'c8y-group-open'\"\n              class=\"c8y-icon-duocolor\"\n              *ngIf=\"result.c8y_IsDeviceGroup\"\n            ></i>\n          </c8y-li-icon>\n          {{ result.name || '--' }}\n        </c8y-li>\n\n        <!-- Search results -->\n        <c8y-li *ngIf=\"term.length !== 0\" class=\"p-l-24 p-r-24\" [selectable]=\"false\">\n          <div class=\"legend form-block\">\n            <span translate>Search results</span>\n          </div>\n        </c8y-li>\n        <c8y-li\n          *c8yFor=\"\n            let result of results$;\n            loadMore: 'auto';\n            pipe: filterPipe;\n            notFound: notFoundTemplate;\n            loadingTemplate: loading;\n            loadNextLabel: 'Find more\u2026'\n          \"\n          class=\"c8y-list__item--link  m-l-16 m-r-16\"\n          (click)=\"open($event, result)\"\n        >\n          <c8y-li-icon>\n            <device-status [mo]=\"result\" *ngIf=\"!result.c8y_IsDeviceGroup\"></device-status>\n            <i\n              [c8yIcon]=\"'c8y-group-open'\"\n              class=\"c8y-icon-duocolor\"\n              *ngIf=\"result.c8y_IsDeviceGroup\"\n            ></i>\n          </c8y-li-icon>\n          {{ result.name || '--' }}\n        </c8y-li>\n\n        <!-- No search results found entry -->\n        <ng-template #notFoundTemplate>\n          <c8y-li *ngIf=\"noMatch\" class=\"p-16 c8y-empty-state\" [selectable]=\"false\">\n            <c8y-li-icon [icon]=\"'search'\"></c8y-li-icon>\n            <p><strong translate>No match found.</strong></p>\n            <small translate>\n              Use a filter or go to the asset data table to show all devices and groups.\n            </small>\n          </c8y-li>\n        </ng-template>\n\n        <!-- loading bar first entries -->\n        <c8y-li *ngIf=\"isLoading\" class=\"p-t-32 p-b-0 p-relative\">\n          <div class=\"spinner\" style=\"right:0;\">\n            <div class=\"rect1\"></div>\n            <div class=\"rect2\"></div>\n            <div class=\"rect3\"></div>\n            <div class=\"rect4\"></div>\n            <div class=\"rect5\"></div>\n          </div>\n        </c8y-li>\n\n        <!-- loading bar for loading more entries (inventory roles) -->\n        <ng-template #loading>\n          <c8y-li class=\"text-center p-t-32 p-b-0 p-relative\">\n            <div class=\"spinner\" style=\"right:0;\">\n              <div class=\"rect1\"></div>\n              <div class=\"rect2\"></div>\n              <div class=\"rect3\"></div>\n              <div class=\"rect4\"></div>\n              <div class=\"rect5\"></div>\n            </div>\n          </c8y-li>\n        </ng-template>\n\n        <!-- more filter possibilities -->\n        <c8y-li class=\"m-t-24 bg-gray-lighter p-t-16 p-b-16 p-l-24 p-r-24\" [selectable]=\"false\">\n          <div class=\"flex-row\">\n            <i c8yIcon=\"info-circle\" class=\"text-info m-r-4\"></i>\n            <p translate class=\"m-r-8\">Need more filter possibilities?</p>\n            <button\n              type=\"button\"\n              class=\"m-l-auto btn btn-default btn-sm\"\n              translate\n              (mousedown)=\"openSearch()\"\n            >\n              Go to the asset data table\n            </button>\n          </div>\n        </c8y-li>\n      </c8y-typeahead>\n    </form>\n  </div>\n</div>\n"
                },] }
    ];
    SearchBoxComponent.ctorParameters = function () { return [
        { type: router.Router },
        { type: client.InventoryService },
        { type: deviceGrid.DeviceGridService },
        { type: AssetSearchService }
    ]; };
    SearchBoxComponent.propDecorators = {
        typeahead: [{ type: i0.ViewChild, args: [i3.TypeaheadComponent, { static: false },] }],
        dropdown: [{ type: i0.ViewChild, args: ['dropdown', { static: false },] }]
    };

    var SearchGridComponent = /** @class */ (function () {
        function SearchGridComponent(searchService, bsModalService, smartGroupsService, subAssetsGridService) {
            this.searchService = searchService;
            this.bsModalService = bsModalService;
            this.smartGroupsService = smartGroupsService;
            this.subAssetsGridService = subAssetsGridService;
            this.title = '';
            this.loadingItemsLabel = i3.gettext('Loading results…');
            this.selectable = false;
            this.onColumnsChange = new i0.EventEmitter();
            this.searchText = '';
            this.pagination = this.searchService.getDefaultPagination();
            this.bulkActionControls = this.searchService.getDefaultBulkActionControls();
            this.refresh = new i0.EventEmitter();
            this.sizeCount = 0;
        }
        Object.defineProperty(SearchGridComponent.prototype, "_columns", {
            set: function (value) {
                if (value) {
                    this.columns = value;
                }
                else {
                    this.columns = this.searchService.getDefaultColumns();
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SearchGridComponent.prototype, "_pagination", {
            set: function (value) {
                if (value) {
                    this.pagination = value;
                }
                else {
                    this.pagination = this.searchService.getDefaultPagination();
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SearchGridComponent.prototype, "_actionControls", {
            set: function (value) {
                if (value) {
                    this.actionControls = value;
                }
                else {
                    this.actionControls = this.searchService.getDefaultActionControls();
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SearchGridComponent.prototype, "_bulkActionControls", {
            set: function (value) {
                if (value) {
                    this.bulkActionControls = value;
                }
                else {
                    this.bulkActionControls = this.searchService.getDefaultBulkActionControls();
                }
            },
            enumerable: false,
            configurable: true
        });
        SearchGridComponent.prototype.ngOnInit = function () {
            if (!this.filteringName) {
                this.columns = this.searchService.getDefaultColumns();
            }
            else {
                this.columns = [
                    new subAssets.AssetTypeGridColumn({ sortOrder: 'desc' }),
                    new deviceGrid.NameDeviceGridColumn({
                        sortOrder: 'asc',
                        filter: { externalFilterQuery: { names: [this.filteringName] } }
                    }),
                    new deviceGrid.ModelDeviceGridColumn(),
                    new deviceGrid.SerialNumberDeviceGridColumn({ visible: false }),
                    new deviceGrid.RegistrationDateDeviceGridColumn({ visible: false }),
                    new deviceGrid.SystemIdDeviceGridColumn({ visible: false }),
                    new deviceGrid.ImeiDeviceGridColumn({ visible: false }),
                    new deviceGrid.AlarmsDeviceGridColumn()
                ];
            }
            this.serverSideDataCallback = this.onDataSourceModifier.bind(this);
            this.setActionControls();
        };
        SearchGridComponent.prototype.trackByName = function (_index, column) {
            return column.name;
        };
        SearchGridComponent.prototype.onDataSourceModifier = function (dataSourceModifier) {
            return __awaiter(this, void 0, void 0, function () {
                var response, res, data, paging, filteredData;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!dataSourceModifier.searchText) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.searchService.search(dataSourceModifier.searchText, dataSourceModifier.pagination)];
                        case 1:
                            response = _a.sent();
                            return [3 /*break*/, 4];
                        case 2: return [4 /*yield*/, this.searchService.getData(dataSourceModifier.columns, dataSourceModifier.pagination, undefined)];
                        case 3:
                            response = _a.sent();
                            _a.label = 4;
                        case 4:
                            res = response.res, data = response.data, paging = response.paging;
                            filteredData = this.searchService.filterOnlyAssets(data);
                            if (paging.currentPage === 1) {
                                this.sizeCount = 0;
                            }
                            this.sizeCount += filteredData.length;
                            this.onColumnsChange.emit(dataSourceModifier.columns);
                            return [2 /*return*/, {
                                    res: res,
                                    data: filteredData,
                                    paging: paging,
                                    filteredSize: this.sizeCount,
                                    size: undefined
                                }];
                    }
                });
            });
        };
        SearchGridComponent.prototype.setActionControls = function () {
            var _this = this;
            var actionControls = [];
            var deleteAction = {
                type: "DELETE" /* Delete */,
                callback: function (asset) { return _this.onDeleteAsset(asset, _this.parentGroup); }
            };
            actionControls.push(deleteAction);
            if (!this.actionControls) {
                this.actionControls = actionControls;
            }
        };
        SearchGridComponent.prototype.updateFiltering = function (columnNames, action) {
            var type = action.type;
            if (type === i3.FilteringActionType.ResetFilter) {
                this.dataGrid.clearFilters();
            }
            else {
                this.dataGrid.updateFiltering(columnNames, action, false);
            }
        };
        SearchGridComponent.prototype.configChange = function (config) {
            this.searchService.saveConfig(config);
        };
        SearchGridComponent.prototype.onDeleteAsset = function (asset, parentRef) {
            var _this = this;
            var initialState = {
                showWithDeviceUserCheckbox: this.subAssetsGridService.shouldShowWithDeviceUserCheckbox(asset),
                asset: asset,
                showWithCascadeCheckbox: !this.smartGroupsService.isSmartGroup(asset) &&
                    !this.smartGroupsService.isSmartGroupV2(asset)
            };
            var modalRef = this.bsModalService.show(subAssets.DeleteAssetsModalComponent, { initialState: initialState });
            modalRef.content.closeSubject.subscribe(function (result) { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!result) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.subAssetsGridService.deleteAsset(asset, parentRef, result)];
                        case 1:
                            _a.sent();
                            this.refresh.emit();
                            _a.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            }); });
        };
        return SearchGridComponent;
    }());
    SearchGridComponent.decorators = [
        { type: i0.Component, args: [{
                    selector: 'c8y-search-grid',
                    template: "<div class=\"card--grid--fullpage\">\n  <c8y-data-grid\n    [title]=\"'Search results' | translate\"\n    [loadingItemsLabel]=\"loadingItemsLabel\"\n    [columns]=\"columns\"\n    [pagination]=\"pagination\"\n    [actionControls]=\"actionControls\"\n    [selectable]=\"selectable\"\n    [bulkActionControls]=\"bulkActionControls\"\n    [serverSideDataCallback]=\"serverSideDataCallback\"\n    [infiniteScroll]=\"'auto'\"\n    [showSearch]=\"true\"\n    [searchText]=\"searchText\"\n    [refresh]=\"refresh\"\n    (onConfigChange)=\"configChange($event)\"\n    class=\"d-contents\"\n  >\n    <ng-container *ngFor=\"let column of columns; trackBy: trackByName\">\n      <c8y-column [name]=\"column.name\"></c8y-column>\n    </ng-container>\n    <div class=\"c8y-empty-state\">\n      <h1 c8yIcon=\"search\"></h1>\n      <div>\n        <p>\n          <strong>{{ 'No items found.' | translate }}</strong>\n        </p>\n        <small>{{ 'Change your search or filter criteria.' | translate }}</small>\n      </div>\n    </div>\n  </c8y-data-grid>\n</div>\n"
                },] }
    ];
    SearchGridComponent.ctorParameters = function () { return [
        { type: AssetSearchService },
        { type: modal.BsModalService },
        { type: client.SmartGroupsService },
        { type: subAssets.SubAssetsService }
    ]; };
    SearchGridComponent.propDecorators = {
        parentGroup: [{ type: i0.Input, args: ['parent-group',] }],
        title: [{ type: i0.Input }],
        loadingItemsLabel: [{ type: i0.Input }],
        _columns: [{ type: i0.Input, args: ['columns',] }],
        _pagination: [{ type: i0.Input, args: ['pagination',] }],
        _actionControls: [{ type: i0.Input, args: ['actionControls',] }],
        selectable: [{ type: i0.Input }],
        _bulkActionControls: [{ type: i0.Input, args: ['bulkActionControls',] }],
        onColumnsChange: [{ type: i0.Output }],
        searchText: [{ type: i0.Input }],
        filteringName: [{ type: i0.Input }],
        dataGrid: [{ type: i0.ViewChild, args: [i3.DataGridComponent, { static: true },] }]
    };

    var SearchResultsComponent = /** @class */ (function () {
        function SearchResultsComponent(route, alert) {
            this.route = route;
            this.alert = alert;
            this.filter = '';
            this.searchTerm = '';
            this.unsubscribe$ = new rxjs.Subject();
        }
        SearchResultsComponent.prototype.ngOnInit = function () {
            var _this = this;
            this.route.queryParams.subscribe(function (params) {
                if (params.filter) {
                    _this.filteringName = params.filter;
                }
            });
        };
        SearchResultsComponent.prototype.ngAfterViewInit = function () {
            var _this = this;
            this.route.queryParams
                .pipe(operators.takeUntil(this.unsubscribe$))
                .subscribe(function (_a) {
                var filter = _a.filter, search = _a.search;
                return _this.onQueryParamsChange(filter, search);
            });
            this.searchGrid.dataGrid.searchText$.pipe(operators.takeUntil(this.unsubscribe$)).subscribe(function (text) {
                if (text) {
                    _this.resetFilter();
                }
                _this.searchTerm = text;
            });
            this.searchGrid.dataGrid.onFilter
                .pipe(operators.takeUntil(this.unsubscribe$))
                .subscribe(function () { return _this.resetSearch(); });
            // to prevent race condition (search empty):
            this.searchTerm = this.route.snapshot.queryParams.search || '';
        };
        SearchResultsComponent.prototype.resetSearch = function () {
            this.searchTerm = '';
            if (this.searchTerm) {
                this.alert.add({
                    text: i3.gettext('Search reset. Full text search does not support filtering.'),
                    type: i3.Status.WARNING,
                    timeout: 5000
                });
            }
        };
        SearchResultsComponent.prototype.resetFilter = function () {
            this.filter = '';
            if (this.searchGrid.dataGrid.filteringApplied) {
                this.alert.add({
                    text: i3.gettext('Filter reset. Full text search does not support filtering.'),
                    type: i3.Status.WARNING,
                    timeout: 5000
                });
                this.searchGrid.dataGrid.clearFilters();
            }
        };
        SearchResultsComponent.prototype.ngOnDestroy = function () {
            this.unsubscribe$.next();
            this.unsubscribe$.complete();
        };
        SearchResultsComponent.prototype.onQueryParamsChange = function (filter, searchTerm) {
            if (!this.shouldFilter(filter) && searchTerm) {
                this.search(searchTerm);
            }
            else if (this.shouldFilter(filter) && searchTerm) {
                this.search(searchTerm);
            }
        };
        SearchResultsComponent.prototype.shouldFilter = function (filter) {
            if (!filter) {
                return false;
            }
            this.resetSearch();
            this.filter = filter || '';
            this.searchGrid.updateFiltering(['name'], {
                type: i3.FilteringActionType.ApplyFilter,
                payload: {
                    filteringModifier: {
                        externalFilterQuery: {
                            names: [this.filter]
                        }
                    }
                }
            });
            return true;
        };
        SearchResultsComponent.prototype.search = function (searchTerm) {
            this.searchTerm = searchTerm || '';
            this.searchGrid.dataGrid.searchText$.next(this.searchTerm);
        };
        return SearchResultsComponent;
    }());
    SearchResultsComponent.decorators = [
        { type: i0.Component, args: [{
                    selector: 'c8y-search-results',
                    template: "<c8y-title>\n  <span translate class=\"p-r-4\">Search</span>\n  <small\n    ngNonBindable\n    translate\n    *ngIf=\"searchTerm\"\n    [translateParams]=\"{\n      searchHint: searchTerm\n    }\"\n    >searching \"{{ searchHint }}\"</small\n  >\n  <small\n    ngNonBindable\n    translate\n    *ngIf=\"filter\"\n    [translateParams]=\"{\n      filterHint: filter\n    }\"\n    >filtered by \"{{ filterHint }}\"</small\n  >\n</c8y-title>\n\n<c8y-search-grid [searchText]=\"searchTerm\" [filteringName]=\"filteringName\"></c8y-search-grid>\n"
                },] }
    ];
    SearchResultsComponent.ctorParameters = function () { return [
        { type: router.ActivatedRoute },
        { type: i3.AlertService }
    ]; };
    SearchResultsComponent.propDecorators = {
        searchGrid: [{ type: i0.ViewChild, args: [SearchGridComponent, { static: true },] }]
    };

    var ɵ0 = [
        {
            path: 'assetsearch',
            component: SearchResultsComponent
        }
    ], ɵ1 = [
        {
            template: SearchBoxComponent
        }
    ];
    var SearchModule = /** @class */ (function () {
        function SearchModule() {
        }
        return SearchModule;
    }());
    SearchModule.decorators = [
        { type: i0.NgModule, args: [{
                    declarations: [SearchResultsComponent, SearchBoxComponent, SearchGridComponent],
                    imports: [i3.CoreModule, deviceGrid.DeviceGridModule, dropdown.BsDropdownModule],
                    entryComponents: [SearchResultsComponent, SearchBoxComponent],
                    exports: [SearchResultsComponent, SearchBoxComponent, SearchGridComponent],
                    providers: [
                        AssetSearchService,
                        {
                            provide: i3.HOOK_ROUTE,
                            useValue: ɵ0,
                            multi: true
                        },
                        {
                            provide: i3.HOOK_SEARCH,
                            useValue: ɵ1,
                            multi: true
                        }
                    ]
                },] }
    ];

    /**
     * Generated bundle index. Do not edit.
     */

    exports.AssetSearchService = AssetSearchService;
    exports.SearchBoxComponent = SearchBoxComponent;
    exports.SearchGridComponent = SearchGridComponent;
    exports.SearchModule = SearchModule;
    exports.SearchResultsComponent = SearchResultsComponent;
    exports["ɵ0"] = ɵ0;
    exports["ɵ1"] = ɵ1;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=c8y-ngx-components-search.umd.js.map
