import { Component, EventEmitter, Output, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AlertService, gettext, ValidationPattern } from '@c8y/ngx-components';
import { PRODUCT_EXPERIENCE_REPOSITORY_SHARED, RepositoryService, RepositoryType } from '@c8y/ngx-components/repository/shared';
import { assign, get, isUndefined } from 'lodash-es';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { BehaviorSubject, from } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap, tap } from 'rxjs/operators';
import * as i0 from "@angular/core";
import * as i1 from "ngx-bootstrap/modal";
import * as i2 from "@c8y/ngx-components/repository/shared";
import * as i3 from "@c8y/ngx-components";
import * as i4 from "@angular/common";
import * as i5 from "@angular/forms";
import * as i6 from "ngx-bootstrap/popover";
export class AddFirmwareModalComponent {
    constructor(modal, repositoryService, alert) {
        this.modal = modal;
        this.repositoryService = repositoryService;
        this.alert = alert;
        this.PRODUCT_EXPERIENCE = PRODUCT_EXPERIENCE_REPOSITORY_SHARED;
        this.saved = new EventEmitter();
        this.onInput = new BehaviorSubject('');
        this.model = {
            selected: undefined,
            version: undefined,
            description: undefined,
            deviceType: undefined,
            binary: {
                file: undefined,
                url: undefined
            }
        };
        this.saving = false;
        this.firmwarePreselected = false;
        this.textForFirmwareUrlPopover = gettext(`Path for binaries can vary depending on device agent implementation, for example:
    /firmware/binaries/firmware1.bin
    https://firmware/binary/123
    ftp://firmware/binary/123.tar.gz
  `);
        this.ValidationPattern = ValidationPattern;
    }
    ngOnInit() {
        this.setInitialState();
        this.loadFirmwares();
    }
    setInitialState() {
        if (this.model.selected) {
            this.firmwarePreselected = true;
        }
    }
    loadFirmwares() {
        this.inputSubscription$ = this.onInput
            .pipe(tap(() => {
            if (!this.firmwarePreselected) {
                this.model.description = null;
                if (this.form) {
                    this.form.form.get('description').reset();
                }
            }
        }), debounceTime(300), distinctUntilChanged(), switchMap(searchStr => this.getFirmwareResult(searchStr)))
            .subscribe(result => {
            this.firmwaresResult = result;
        });
    }
    getFirmwareResult(searchStr) {
        return from(this.repositoryService.listRepositoryEntries(RepositoryType.FIRMWARE, {
            partialName: searchStr,
            skipLegacy: true
        }));
    }
    async save() {
        this.saving = true;
        this.repositoryService
            .create(this.model, RepositoryType.FIRMWARE)
            .then(savedFirmware => {
            this.successMsg();
            this.saving = false;
            this.saved.next(savedFirmware);
            this.cancel();
        })
            .catch(e => {
            this.saving = false;
            this.saved.error(e);
            this.cancel();
        });
    }
    successMsg() {
        const msg = gettext('Firmware added.');
        this.alert.success(msg);
    }
    cancel() {
        this.modal.hide();
        this.saved.complete();
    }
    ngOnDestroy() {
        this.inputSubscription$.unsubscribe();
    }
    onFile(dropped) {
        if (!isUndefined(dropped.url)) {
            this.model.binary = {
                url: dropped.url
            };
            return;
        }
        else if (dropped.droppedFiles) {
            this.model.binary = {
                file: dropped.droppedFiles[0].file
            };
            return;
        }
        else {
            this.model.binary = {
                file: undefined,
                url: undefined
            };
        }
    }
    onFirmwareSelect(firmware) {
        assign(this.model, {
            selected: firmware,
            description: firmware.description,
            deviceType: get(firmware, 'c8y_Filter.type')
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AddFirmwareModalComponent, deps: [{ token: i1.BsModalRef }, { token: i2.RepositoryService }, { token: i3.AlertService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: AddFirmwareModalComponent, selector: "c8y-add-firmware-software-modal", outputs: { saved: "saved" }, viewQueries: [{ propertyName: "form", first: true, predicate: ["firmwareForm"], descendants: true }], ngImport: i0, template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'c8y-firmware'\"></i>\n    <div class=\"modal-title\" translate id=\"addFirmwareModalTitle\">Add firmware</div>\n  </div>\n  <div class=\"p-16 text-center separator-bottom\" *ngIf=\"!firmwarePreselected\">\n    <p class=\"text-medium text-16 m-0\" translate>Select or create new firmware</p>\n  </div>\n  <form\n    class=\"d-contents\"\n    autocomplete=\"off\"\n    #firmwareForm=\"ngForm\"\n    (ngSubmit)=\"firmwareForm.form.valid && save()\"\n  >\n    <div class=\"modal-inner-scroll\">\n      <div class=\"modal-body\" id=\"addFirmwareModalDescription\">\n        <div [hidden]=\"firmwarePreselected\">\n          <c8y-form-group>\n            <label for=\"firmwareName\" translate>Firmware</label>\n            <c8y-typeahead\n              [(ngModel)]=\"model.selected\"\n              name=\"firmwareName\"\n              placeholder=\"{{ 'Select or enter' | translate }}\"\n              data-cy=\"add-firmware-modal--input-name\"\n              (onSearch)=\"onInput.next($event)\"\n              [required]=\"true\"\n            >\n              <c8y-li\n                *c8yFor=\"\n                  let firmware of firmwaresResult;\n                  loadMore: 'auto';\n                  notFound: notFoundTemplate\n                \"\n                class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                (click)=\"onFirmwareSelect(firmware)\"\n                [active]=\"model.selected === firmware\"\n              >\n                <c8y-highlight\n                  [text]=\"firmware.name || '--'\"\n                  [pattern]=\"onInput | async\"\n                ></c8y-highlight>\n              </c8y-li>\n              <ng-template #notFoundTemplate>\n                <c8y-li class=\"bg-level-2 p-8\" *ngIf=\"(onInput | async)?.length > 0\">\n                  <span translate>No match found.</span>\n                  <button\n                    class=\"btn btn-primary btn-xs m-l-8\"\n                    type=\"button\"\n                    title=\"{{ 'Add new`firmware`' | translate }}\"\n                    translate\n                  >\n                    Add new`firmware`\n                  </button>\n                </c8y-li>\n              </ng-template>\n            </c8y-typeahead>\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label for=\"firmwareDescription\" translate>Description</label>\n            <input\n              id=\"firmwareDescription\"\n              data-cy=\"add-firmware-modal--input-description\"\n              class=\"form-control\"\n              autocomplete=\"off\"\n              name=\"description\"\n              [(ngModel)]=\"model.description\"\n              placeholder=\"{{ 'e.g. Firmware for hardware revision B' | translate }}\"\n              [disabled]=\"model.selected?.id\"\n              [required]=\"true\"\n              [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n            />\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label class=\"control-label\" for=\"firmwareDeviceTypeFilter\">\n              {{ 'Device type filter' | translate }}\n              <button\n                class=\"btn-help\"\n                type=\"button\"\n                [attr.aria-label]=\"'Help' | translate\"\n                popover=\"{{\n                  'If the filter is set, the firmware will show up for installation only for devices of that type. If no filter is set, it will be available for all devices.'\n                    | translate\n                }}\"\n                triggers=\"focus\"\n                placement=\"right\"\n                container=\"body\"\n              ></button>\n            </label>\n            <input\n              id=\"firmwareDeviceTypeFilter\"\n              data-cy=\"add-firmware-modal--firmwareDeviceTypeFilter\"\n              class=\"form-control\"\n              name=\"firmwareDeviceTypeFilter\"\n              [(ngModel)]=\"model.deviceType\"\n              placeholder=\"{{ 'e.g.' | translate }} c8y_Linux\"\n              [disabled]=\"model.selected?.id\"\n              [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n            />\n          </c8y-form-group>\n        </div>\n\n        <c8y-form-group>\n          <label for=\"firmwareVersion\" translate>Version</label>\n          <input\n            id=\"firmwareVersion\"\n            data-cy=\"add-firmware-modal--firmwareVersion\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            name=\"version\"\n            [(ngModel)]=\"model.version\"\n            placeholder=\"{{ 'e.g.' | translate }} 1.0.0\"\n            [required]=\"true\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div class=\"legend form-block m-t-40\" translate>Firmware file</div>\n          <c8y-file-picker\n            [maxAllowedFiles]=\"1\"\n            (onFilesPicked)=\"onFile($event)\"\n            [fileUrlPopover]=\"textForFirmwareUrlPopover\"\n          ></c8y-file-picker>\n        </c8y-form-group>\n      </div>\n    </div>\n    <div class=\"modal-footer\">\n      <button\n        class=\"btn btn-default\"\n        type=\"button\"\n        title=\"{{ 'Cancel' | translate }}\"\n        data-cy=\"add-firmware-modal--cancel-btn\"\n        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n        translate\n      >\n        Cancel\n      </button>\n\n      <button\n        class=\"btn btn-primary\"\n        type=\"submit\"\n        title=\"{{ 'Add firmware' | translate }}\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !firmwareForm.form.valid ||\n          firmwareForm.form.pristine ||\n          saving ||\n          (!model.binary?.url && !model.binary?.file)\n        \"\n        [actionName]=\"PRODUCT_EXPERIENCE.FIRMWARE.EVENTS.REPOSITORY\"\n        [actionData]=\"{\n          component: PRODUCT_EXPERIENCE.FIRMWARE.COMPONENTS.ADD_FIRMWARE_MODAL,\n          result:\n            firmwarePreselected || model.selected?.id\n              ? PRODUCT_EXPERIENCE.FIRMWARE.RESULTS.ADD_FIRMWARE_VERSION\n              : PRODUCT_EXPERIENCE.FIRMWARE.RESULTS.ADD_FIRMWARE\n        }\"\n        translate\n        c8yProductExperience\n      >\n        Add firmware\n      </button>\n    </div>\n  </form>\n</div>\n", dependencies: [{ kind: "directive", type: i4.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i3.IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "directive", type: i3.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i3.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: i3.HighlightComponent, selector: "c8y-highlight", inputs: ["pattern", "text", "elementClass", "shouldTrimPattern"] }, { kind: "component", type: i3.TypeaheadComponent, selector: "c8y-typeahead", inputs: ["required", "maxlength", "disabled", "allowFreeEntries", "placeholder", "displayProperty", "icon", "name", "autoClose", "hideNew", "container", "selected", "highlightFirstItem"], outputs: ["onSearch", "onIconClick"] }, { kind: "directive", type: i5.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i5.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i5.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i5.PatternValidator, selector: "[pattern][formControlName],[pattern][formControl],[pattern][ngModel]", inputs: ["pattern"] }, { kind: "directive", type: i5.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i5.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "component", type: i3.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i3.RequiredInputPlaceholderDirective, selector: "input[required], input[formControlName]" }, { kind: "component", type: i3.ListItemComponent, selector: "c8y-list-item, c8y-li", inputs: ["active", "highlighted", "emptyActions", "dense", "collapsed", "selectable"], outputs: ["collapsedChange"] }, { kind: "component", type: i3.FilePickerComponent, selector: "c8y-file-picker", inputs: ["maxAllowedFiles", "uploadChoice", "fileUrl", "fileBinary", "config", "filePickerIndex", "fileUrlPopover"], outputs: ["onFilesPicked"] }, { kind: "directive", type: i3.ProductExperienceDirective, selector: "[c8yProductExperience]", inputs: ["actionName", "actionData", "inherit", "suppressDataOverriding"] }, { kind: "directive", type: i6.PopoverDirective, selector: "[popover]", inputs: ["adaptivePosition", "boundariesElement", "popover", "popoverContext", "popoverTitle", "placement", "outsideClick", "triggers", "container", "containerClass", "isOpen", "delay"], outputs: ["onShown", "onHidden"], exportAs: ["bs-popover"] }, { kind: "pipe", type: i4.AsyncPipe, name: "async" }, { kind: "pipe", type: i3.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AddFirmwareModalComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-add-firmware-software-modal', template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'c8y-firmware'\"></i>\n    <div class=\"modal-title\" translate id=\"addFirmwareModalTitle\">Add firmware</div>\n  </div>\n  <div class=\"p-16 text-center separator-bottom\" *ngIf=\"!firmwarePreselected\">\n    <p class=\"text-medium text-16 m-0\" translate>Select or create new firmware</p>\n  </div>\n  <form\n    class=\"d-contents\"\n    autocomplete=\"off\"\n    #firmwareForm=\"ngForm\"\n    (ngSubmit)=\"firmwareForm.form.valid && save()\"\n  >\n    <div class=\"modal-inner-scroll\">\n      <div class=\"modal-body\" id=\"addFirmwareModalDescription\">\n        <div [hidden]=\"firmwarePreselected\">\n          <c8y-form-group>\n            <label for=\"firmwareName\" translate>Firmware</label>\n            <c8y-typeahead\n              [(ngModel)]=\"model.selected\"\n              name=\"firmwareName\"\n              placeholder=\"{{ 'Select or enter' | translate }}\"\n              data-cy=\"add-firmware-modal--input-name\"\n              (onSearch)=\"onInput.next($event)\"\n              [required]=\"true\"\n            >\n              <c8y-li\n                *c8yFor=\"\n                  let firmware of firmwaresResult;\n                  loadMore: 'auto';\n                  notFound: notFoundTemplate\n                \"\n                class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                (click)=\"onFirmwareSelect(firmware)\"\n                [active]=\"model.selected === firmware\"\n              >\n                <c8y-highlight\n                  [text]=\"firmware.name || '--'\"\n                  [pattern]=\"onInput | async\"\n                ></c8y-highlight>\n              </c8y-li>\n              <ng-template #notFoundTemplate>\n                <c8y-li class=\"bg-level-2 p-8\" *ngIf=\"(onInput | async)?.length > 0\">\n                  <span translate>No match found.</span>\n                  <button\n                    class=\"btn btn-primary btn-xs m-l-8\"\n                    type=\"button\"\n                    title=\"{{ 'Add new`firmware`' | translate }}\"\n                    translate\n                  >\n                    Add new`firmware`\n                  </button>\n                </c8y-li>\n              </ng-template>\n            </c8y-typeahead>\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label for=\"firmwareDescription\" translate>Description</label>\n            <input\n              id=\"firmwareDescription\"\n              data-cy=\"add-firmware-modal--input-description\"\n              class=\"form-control\"\n              autocomplete=\"off\"\n              name=\"description\"\n              [(ngModel)]=\"model.description\"\n              placeholder=\"{{ 'e.g. Firmware for hardware revision B' | translate }}\"\n              [disabled]=\"model.selected?.id\"\n              [required]=\"true\"\n              [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n            />\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label class=\"control-label\" for=\"firmwareDeviceTypeFilter\">\n              {{ 'Device type filter' | translate }}\n              <button\n                class=\"btn-help\"\n                type=\"button\"\n                [attr.aria-label]=\"'Help' | translate\"\n                popover=\"{{\n                  'If the filter is set, the firmware will show up for installation only for devices of that type. If no filter is set, it will be available for all devices.'\n                    | translate\n                }}\"\n                triggers=\"focus\"\n                placement=\"right\"\n                container=\"body\"\n              ></button>\n            </label>\n            <input\n              id=\"firmwareDeviceTypeFilter\"\n              data-cy=\"add-firmware-modal--firmwareDeviceTypeFilter\"\n              class=\"form-control\"\n              name=\"firmwareDeviceTypeFilter\"\n              [(ngModel)]=\"model.deviceType\"\n              placeholder=\"{{ 'e.g.' | translate }} c8y_Linux\"\n              [disabled]=\"model.selected?.id\"\n              [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n            />\n          </c8y-form-group>\n        </div>\n\n        <c8y-form-group>\n          <label for=\"firmwareVersion\" translate>Version</label>\n          <input\n            id=\"firmwareVersion\"\n            data-cy=\"add-firmware-modal--firmwareVersion\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            name=\"version\"\n            [(ngModel)]=\"model.version\"\n            placeholder=\"{{ 'e.g.' | translate }} 1.0.0\"\n            [required]=\"true\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div class=\"legend form-block m-t-40\" translate>Firmware file</div>\n          <c8y-file-picker\n            [maxAllowedFiles]=\"1\"\n            (onFilesPicked)=\"onFile($event)\"\n            [fileUrlPopover]=\"textForFirmwareUrlPopover\"\n          ></c8y-file-picker>\n        </c8y-form-group>\n      </div>\n    </div>\n    <div class=\"modal-footer\">\n      <button\n        class=\"btn btn-default\"\n        type=\"button\"\n        title=\"{{ 'Cancel' | translate }}\"\n        data-cy=\"add-firmware-modal--cancel-btn\"\n        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n        translate\n      >\n        Cancel\n      </button>\n\n      <button\n        class=\"btn btn-primary\"\n        type=\"submit\"\n        title=\"{{ 'Add firmware' | translate }}\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !firmwareForm.form.valid ||\n          firmwareForm.form.pristine ||\n          saving ||\n          (!model.binary?.url && !model.binary?.file)\n        \"\n        [actionName]=\"PRODUCT_EXPERIENCE.FIRMWARE.EVENTS.REPOSITORY\"\n        [actionData]=\"{\n          component: PRODUCT_EXPERIENCE.FIRMWARE.COMPONENTS.ADD_FIRMWARE_MODAL,\n          result:\n            firmwarePreselected || model.selected?.id\n              ? PRODUCT_EXPERIENCE.FIRMWARE.RESULTS.ADD_FIRMWARE_VERSION\n              : PRODUCT_EXPERIENCE.FIRMWARE.RESULTS.ADD_FIRMWARE\n        }\"\n        translate\n        c8yProductExperience\n      >\n        Add firmware\n      </button>\n    </div>\n  </form>\n</div>\n" }]
        }], ctorParameters: () => [{ type: i1.BsModalRef }, { type: i2.RepositoryService }, { type: i3.AlertService }], propDecorators: { form: [{
                type: ViewChild,
                args: ['firmwareForm', { static: false }]
            }], saved: [{
                type: Output
            }] } });
//# sourceMappingURL=data:application/json;base64, 