import { Component, ViewChild } from '@angular/core';
import { LpwanSetDeviceProtocolService } from './lpwan-set-device-protocol.service';
import { AlertService, gettext } from '@c8y/ngx-components';
import { InventoryService } from '@c8y/client';
import { Router } from '@angular/router';
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import { NgForm } from '@angular/forms';
import * as i0 from "@angular/core";
import * as i1 from "./lpwan-set-device-protocol.service";
import * as i2 from "@c8y/ngx-components";
import * as i3 from "@angular/router";
import * as i4 from "@c8y/client";
import * as i5 from "@angular/common";
import * as i6 from "@angular/forms";
import * as i7 from "./lpwan-set-connections.component";
export class LpwanAssignDeviceProtocolComponent {
    constructor(lpwanService, alertService, router, inventoryService) {
        this.lpwanService = lpwanService;
        this.alertService = alertService;
        this.router = router;
        this.inventoryService = inventoryService;
        this.filterProtocols = pipe();
        this.pattern = '';
    }
    async ngOnInit() {
        await this.reload();
        this.setPipe('');
    }
    setPipe(filterStr) {
        this.pattern = filterStr;
        this.filterProtocols = pipe(map(protocols => protocols.filter(protocol => (!this.currentProtocol || this.currentProtocol.id !== protocol.id) &&
            (!filterStr || protocol.name.toLowerCase().indexOf(filterStr.toLowerCase()) > -1))));
    }
    async reload() {
        this.loading = true;
        this.newProtocol = null;
        try {
            await this.loadDevice();
            this.availableProtocols = await this.lpwanService.getAvailableProtocols(this.device);
            this.currentProtocol = await this.lpwanService.getCurrentProtocol(this.device);
        }
        catch (ex) {
            this.alertService.addServerFailure(ex);
        }
        finally {
            this.loading = false;
        }
    }
    async loadDevice() {
        const deviceId = this.router.routerState.snapshot.url.match(/\d+/)[0];
        const { data } = await this.inventoryService.detail(deviceId);
        this.device = data;
    }
    async apply(selectedProtocol) {
        try {
            const moUpdated = (await this.lpwanService.applyProtocol(this.device, selectedProtocol)).res.status === 200;
            await this.reload();
            this.alertService.success(gettext('Device protocol set.'));
            this.lpwanSetDeviceProtocolForm.reset('dirty');
            if (moUpdated) {
                this.refreshCache();
            }
        }
        catch (ex) {
            this.alertService.danger(gettext('Could not set device protocol.'));
        }
    }
    async refreshCache() {
        try {
            await this.lpwanService.refreshCache(this.device);
        }
        catch (ex) {
            // do nothing (refreshing is an optional step)
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: LpwanAssignDeviceProtocolComponent, deps: [{ token: i1.LpwanSetDeviceProtocolService }, { token: i2.AlertService }, { token: i3.Router }, { token: i4.InventoryService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: LpwanAssignDeviceProtocolComponent, selector: "set-device-protocol", viewQueries: [{ propertyName: "lpwanSetDeviceProtocolForm", first: true, predicate: ["lpwanSetDeviceProtocolForm"], descendants: true }], ngImport: i0, template: "<form #lpwanSetDeviceProtocolForm=\"ngForm\">\n  <div class=\"row\">\n    <div class=\"col-md-9\">\n      <div class=\"card card--fullpage\">\n        <div class=\"card-header separator\">\n          <div class=\"card-title\">\n            {{ 'LPWAN configuration' | translate }}\n          </div>\n        </div>\n\n        <div class=\"card-block p-t-24 p-b-8 overflow-visible\">\n          <div *ngIf=\"loading\">\n            <c8y-loading></c8y-loading>\n          </div>\n\n          <div *ngIf=\"!loading\">\n            <div class=\"col-md-6\">\n              <div class=\"form-group\">\n                <label translate>Current device protocol</label>\n                <p class=\"form-control-static\" *ngIf=\"!currentProtocol\">\n                  {{ device.type }}\n                </p>\n                <p\n                  class=\"form-control-static text-truncate\"\n                  *ngIf=\"currentProtocol\"\n                  title=\"{{ currentProtocol.name }}\"\n                >\n                  {{ currentProtocol.name }}\n                </p>\n              </div>\n              <c8y-form-group>\n                <c8y-typeahead\n                  [(ngModel)]=\"newProtocol\"\n                  placeholder=\"{{ 'Select new device protocol' | translate }}\"\n                  (onSearch)=\"setPipe($event)\"\n                  name=\"newProtocol\"\n                  [allowFreeEntries]=\"false\"\n                >\n                  <c8y-li\n                    *c8yFor=\"\n                      let protocol of availableProtocols;\n                      loadMore: 'hidden';\n                      pipe: filterProtocols\n                    \"\n                    class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                    (click)=\"newProtocol = protocol; setPipe('')\"\n                  >\n                    <c8y-highlight [text]=\"protocol.name\" [pattern]=\"pattern\"></c8y-highlight>\n                  </c8y-li>\n                </c8y-typeahead>\n                <c8y-messages>\n                  <c8y-message\n                    name=\"notExisting\"\n                    [text]=\"'Select one of the protocols.' | translate\"\n                  ></c8y-message>\n                </c8y-messages>\n              </c8y-form-group>\n            </div>\n            <set-lns-connections [device]=\"device\"></set-lns-connections>\n          </div>\n        </div>\n\n        <div class=\"card-footer separator\">\n          <button\n            title=\"{{ 'Save' | translate }}\"\n            type=\"submit\"\n            class=\"btn btn-primary\"\n            (click)=\"apply(newProtocol)\"\n            [disabled]=\"!newProtocol\"\n          >\n            {{ 'Save' | translate }}\n          </button>\n        </div>\n      </div>\n    </div>\n  </div>\n</form>\n\u200C\n", dependencies: [{ kind: "directive", type: i2.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i5.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i2.ForOfDirective, selector: "[c8yFor]", inputs: ["c8yForOf", "c8yForLoadMore", "c8yForPipe", "c8yForNotFound", "c8yForMaxIterations", "c8yForLoadingTemplate", "c8yForLoadNextLabel", "c8yForLoadingLabel", "c8yForRealtime", "c8yForRealtimeOptions", "c8yForComparator", "c8yForEnableVirtualScroll", "c8yForVirtualScrollElementSize", "c8yForVirtualScrollStrategy", "c8yForVirtualScrollContainerHeight"], outputs: ["c8yForCount", "c8yForChange", "c8yForLoadMoreComponent"] }, { kind: "component", type: i2.LoadingComponent, selector: "c8y-loading", inputs: ["layout", "progress", "message"] }, { kind: "component", type: i2.HighlightComponent, selector: "c8y-highlight", inputs: ["pattern", "text", "elementClass", "shouldTrimPattern"] }, { kind: "component", type: i2.TypeaheadComponent, selector: "c8y-typeahead", inputs: ["required", "maxlength", "disabled", "allowFreeEntries", "placeholder", "displayProperty", "icon", "name", "autoClose", "hideNew", "container", "selected", "highlightFirstItem"], outputs: ["onSearch", "onIconClick"] }, { kind: "directive", type: i6.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i6.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i6.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i6.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i6.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "component", type: i2.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i2.MessageDirective, selector: "c8y-message", inputs: ["name", "text"] }, { kind: "component", type: i2.MessagesComponent, selector: "c8y-messages", inputs: ["show", "defaults", "helpMessage"] }, { kind: "component", type: i2.ListItemComponent, selector: "c8y-list-item, c8y-li", inputs: ["active", "highlighted", "emptyActions", "dense", "collapsed", "selectable"], outputs: ["collapsedChange"] }, { kind: "component", type: i7.LpwanAssignLnsConnectionsComponent, selector: "set-lns-connections", inputs: ["device"] }, { kind: "pipe", type: i2.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: LpwanAssignDeviceProtocolComponent, decorators: [{
            type: Component,
            args: [{ selector: 'set-device-protocol', template: "<form #lpwanSetDeviceProtocolForm=\"ngForm\">\n  <div class=\"row\">\n    <div class=\"col-md-9\">\n      <div class=\"card card--fullpage\">\n        <div class=\"card-header separator\">\n          <div class=\"card-title\">\n            {{ 'LPWAN configuration' | translate }}\n          </div>\n        </div>\n\n        <div class=\"card-block p-t-24 p-b-8 overflow-visible\">\n          <div *ngIf=\"loading\">\n            <c8y-loading></c8y-loading>\n          </div>\n\n          <div *ngIf=\"!loading\">\n            <div class=\"col-md-6\">\n              <div class=\"form-group\">\n                <label translate>Current device protocol</label>\n                <p class=\"form-control-static\" *ngIf=\"!currentProtocol\">\n                  {{ device.type }}\n                </p>\n                <p\n                  class=\"form-control-static text-truncate\"\n                  *ngIf=\"currentProtocol\"\n                  title=\"{{ currentProtocol.name }}\"\n                >\n                  {{ currentProtocol.name }}\n                </p>\n              </div>\n              <c8y-form-group>\n                <c8y-typeahead\n                  [(ngModel)]=\"newProtocol\"\n                  placeholder=\"{{ 'Select new device protocol' | translate }}\"\n                  (onSearch)=\"setPipe($event)\"\n                  name=\"newProtocol\"\n                  [allowFreeEntries]=\"false\"\n                >\n                  <c8y-li\n                    *c8yFor=\"\n                      let protocol of availableProtocols;\n                      loadMore: 'hidden';\n                      pipe: filterProtocols\n                    \"\n                    class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                    (click)=\"newProtocol = protocol; setPipe('')\"\n                  >\n                    <c8y-highlight [text]=\"protocol.name\" [pattern]=\"pattern\"></c8y-highlight>\n                  </c8y-li>\n                </c8y-typeahead>\n                <c8y-messages>\n                  <c8y-message\n                    name=\"notExisting\"\n                    [text]=\"'Select one of the protocols.' | translate\"\n                  ></c8y-message>\n                </c8y-messages>\n              </c8y-form-group>\n            </div>\n            <set-lns-connections [device]=\"device\"></set-lns-connections>\n          </div>\n        </div>\n\n        <div class=\"card-footer separator\">\n          <button\n            title=\"{{ 'Save' | translate }}\"\n            type=\"submit\"\n            class=\"btn btn-primary\"\n            (click)=\"apply(newProtocol)\"\n            [disabled]=\"!newProtocol\"\n          >\n            {{ 'Save' | translate }}\n          </button>\n        </div>\n      </div>\n    </div>\n  </div>\n</form>\n\u200C\n" }]
        }], ctorParameters: () => [{ type: i1.LpwanSetDeviceProtocolService }, { type: i2.AlertService }, { type: i3.Router }, { type: i4.InventoryService }], propDecorators: { lpwanSetDeviceProtocolForm: [{
                type: ViewChild,
                args: ['lpwanSetDeviceProtocolForm', { static: false }]
            }] } });
//# sourceMappingURL=data:application/json;base64, 