import { Component, EventEmitter, Output, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AlertService, gettext } from '@c8y/ngx-components';
import { PRODUCT_EXPERIENCE_REPOSITORY_SHARED, RepositoryService, RepositoryType } from '@c8y/ngx-components/repository/shared';
import { isUndefined } from 'lodash-es';
import { BsDropdownDirective } from 'ngx-bootstrap/dropdown';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { BehaviorSubject, from, merge, of, pipe } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, shareReplay, 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";
export class AddFirmwarePatchModalComponent {
    constructor(modal, repository, alert) {
        this.modal = modal;
        this.repository = repository;
        this.alert = alert;
        this.PRODUCT_EXPERIENCE = PRODUCT_EXPERIENCE_REPOSITORY_SHARED;
        this.saved = new EventEmitter();
        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.model = {
            selected: undefined,
            dependency: null,
            patchVersion: undefined,
            binary: {
                file: undefined,
                url: undefined
            }
        };
        this.firmwareInput$ = new BehaviorSubject('');
        this.firmwares$ = this.firmwareInput$.pipe(debounceTime(300), distinctUntilChanged(), switchMap(searchStr => from(this.repository.listRepositoryEntries(RepositoryType.FIRMWARE, {
            partialName: searchStr,
            skipLegacy: true
        }))), shareReplay(1));
        this.firmwareSelected$ = new BehaviorSubject(null);
        this.patchDependencyInput$ = new BehaviorSubject('');
        this.saving = false;
        this.firmwarePreselected = false;
        this.baseVersions$ = merge(this.firmwareInput$.pipe(tap(() => {
            this.model.dependency = null;
            if (this.form) {
                this.form.form.get('patchDependency').reset();
            }
        }), switchMap(() => of(null))), this.firmwareSelected$).pipe(switchMap(selectedFirmware => selectedFirmware ? this.repository.listBaseVersions(selectedFirmware) : of(null)), shareReplay(1));
        this.baseVersionsFilterPipe = pipe(switchMap((data) => this.patchDependencyInput$.pipe(map(partialVersion => data.filter((mo) => {
            const version = mo.c8y_Firmware.version?.toLowerCase();
            return (partialVersion.length === 0 || version?.indexOf(partialVersion.toLowerCase()) > -1);
        })))));
    }
    async ngOnInit() {
        this.setInitialState();
    }
    setInitialState() {
        if (this.model.selected) {
            this.firmwarePreselected = true;
            this.firmwareSelected$.next(this.model.selected);
        }
    }
    async save() {
        this.saving = true;
        this.repository
            .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 patch added.');
        this.alert.success(msg);
    }
    cancel() {
        this.modal.hide();
        this.saved.complete();
    }
    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
            };
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: AddFirmwarePatchModalComponent, 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.9", type: AddFirmwarePatchModalComponent, selector: "c8y-add-firmware-patch-modal.component", outputs: { saved: "saved" }, viewQueries: [{ propertyName: "dropdown", first: true, predicate: ["dropdown"], descendants: true }, { propertyName: "form", first: true, predicate: ["firmwarePatchForm"], descendants: true }], ngImport: i0, template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'c8y-firmware'\"></i>\n    <h4 translate id=\"addFirmwarePatchModalTitle\">Add firmware patch</h4>\n  </div>\n  <div class=\"p-16 text-center separator-bottom\" id=\"addFirmwarePatchModalDescription\">\n    <p class=\"text-medium text-16 m-0\" translate>Select a firmware version</p>\n  </div>\n\n  <form\n    class=\"d-contents\"\n    autocomplete=\"off\"\n    #firmwarePatchForm=\"ngForm\"\n    (ngSubmit)=\"firmwarePatchForm.form.valid && save()\"\n  >\n    <div class=\"modal-inner-scroll\">\n      <div class=\"modal-body\">\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              (onSearch)=\"firmwareInput$.next($event)\"\n              [allowFreeEntries]=\"false\"\n              [required]=\"true\"\n            >\n              <c8y-li\n                *c8yFor=\"let firmware of firmwares$ | async; loadMore: 'auto'\"\n                class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                (click)=\"model.selected = firmware; firmwareSelected$.next(firmware)\"\n                [active]=\"model.selected === firmware\"\n              >\n                <c8y-highlight\n                  [text]=\"firmware.name || '--'\"\n                  [pattern]=\"firmwareInput$ | async\"\n                ></c8y-highlight>\n              </c8y-li>\n            </c8y-typeahead>\n            <c8y-messages>\n              <c8y-message\n                name=\"notExisting\"\n                [text]=\"'Select one of the existing firmwares.' | translate\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n\n        <c8y-form-group>\n          <label for=\"patchDependency\" class=\"m-r-8\" translate>Version</label>\n          <c8y-typeahead\n            [ngModel]=\"model.dependency\"\n            name=\"patchDependency\"\n            data-cy=\"add-firmware-patch-modal--patchDependency\"\n            placeholder=\"{{ 'Select or enter' | translate }}\"\n            (onSearch)=\"patchDependencyInput$.next($event)\"\n            [displayProperty]=\"'c8y_Firmware.version'\"\n            [allowFreeEntries]=\"false\"\n            [disabled]=\"\n              (baseVersions$ | async) === null || (baseVersions$ | async)?.data.length === 0\n            \"\n            [required]=\"true\"\n          >\n            <c8y-li\n              *c8yFor=\"\n                let baseVersion of baseVersions$;\n                loadMore: 'auto';\n                pipe: baseVersionsFilterPipe\n              \"\n              class=\"p-l-8 p-r-8 c8y-list__item--link\"\n              (click)=\"model.dependency = baseVersion\"\n              [active]=\"model.dependency === baseVersion\"\n            >\n              <c8y-highlight\n                [text]=\"baseVersion.c8y_Firmware.version || '--'\"\n                [pattern]=\"patchDependencyInput$ | async\"\n              ></c8y-highlight>\n            </c8y-li>\n          </c8y-typeahead>\n          <c8y-messages>\n            <c8y-message\n              name=\"notExisting\"\n              [text]=\"'Select one of the existing versions.' | translate\"\n            ></c8y-message>\n          </c8y-messages>\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label for=\"patchVersion\" translate>Patch</label>\n          <input\n            id=\"patchVersion\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            name=\"patchVersion\"\n            data-cy=\"add-firmware-patch-modal--patchVersion\"\n            [(ngModel)]=\"model.patchVersion\"\n            placeholder=\"{{ 'e.g.' | translate }} 1.0.0\"\n            required\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div class=\"legend form-block m-t-40\" translate>Patch 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        title=\"{{ 'Cancel' | translate }}\"\n        data-cy=\"add-firmware-patch-modal--cancel-btn\"\n        class=\"btn btn-default\"\n        type=\"button\"\n        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n        translate\n      >\n        Cancel\n      </button>\n      <button\n        title=\"{{ 'Add firmware patch' | translate }}\"\n        class=\"btn btn-primary\"\n        type=\"submit\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !firmwarePatchForm.form.valid ||\n          firmwarePatchForm.form.pristine ||\n          (!model.binary?.url && !model.binary?.file) ||\n          saving\n        \"\n        translate\n        c8yProductExperience\n        [actionName]=\"PRODUCT_EXPERIENCE.FIRMWARE.EVENTS.REPOSITORY\"\n        [actionData]=\"{\n          component: PRODUCT_EXPERIENCE.FIRMWARE.COMPONENTS.ADD_FIRMWAR_PATCH_MODAL,\n          result: PRODUCT_EXPERIENCE.FIRMWARE.RESULTS.ADD_FIRMWARE_PATCH\n        }\"\n      >\n        Add firmware patch\n      </button>\n    </div>\n  </form>\n</div>\n", dependencies: [{ kind: "directive", type: i4.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { 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.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.MessageDirective, selector: "c8y-message", inputs: ["name", "text"] }, { kind: "component", type: i3.MessagesComponent, selector: "c8y-messages", inputs: ["show", "defaults", "helpMessage"] }, { 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: "pipe", type: i4.AsyncPipe, name: "async" }, { kind: "pipe", type: i3.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: AddFirmwarePatchModalComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-add-firmware-patch-modal.component', template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'c8y-firmware'\"></i>\n    <h4 translate id=\"addFirmwarePatchModalTitle\">Add firmware patch</h4>\n  </div>\n  <div class=\"p-16 text-center separator-bottom\" id=\"addFirmwarePatchModalDescription\">\n    <p class=\"text-medium text-16 m-0\" translate>Select a firmware version</p>\n  </div>\n\n  <form\n    class=\"d-contents\"\n    autocomplete=\"off\"\n    #firmwarePatchForm=\"ngForm\"\n    (ngSubmit)=\"firmwarePatchForm.form.valid && save()\"\n  >\n    <div class=\"modal-inner-scroll\">\n      <div class=\"modal-body\">\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              (onSearch)=\"firmwareInput$.next($event)\"\n              [allowFreeEntries]=\"false\"\n              [required]=\"true\"\n            >\n              <c8y-li\n                *c8yFor=\"let firmware of firmwares$ | async; loadMore: 'auto'\"\n                class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                (click)=\"model.selected = firmware; firmwareSelected$.next(firmware)\"\n                [active]=\"model.selected === firmware\"\n              >\n                <c8y-highlight\n                  [text]=\"firmware.name || '--'\"\n                  [pattern]=\"firmwareInput$ | async\"\n                ></c8y-highlight>\n              </c8y-li>\n            </c8y-typeahead>\n            <c8y-messages>\n              <c8y-message\n                name=\"notExisting\"\n                [text]=\"'Select one of the existing firmwares.' | translate\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n\n        <c8y-form-group>\n          <label for=\"patchDependency\" class=\"m-r-8\" translate>Version</label>\n          <c8y-typeahead\n            [ngModel]=\"model.dependency\"\n            name=\"patchDependency\"\n            data-cy=\"add-firmware-patch-modal--patchDependency\"\n            placeholder=\"{{ 'Select or enter' | translate }}\"\n            (onSearch)=\"patchDependencyInput$.next($event)\"\n            [displayProperty]=\"'c8y_Firmware.version'\"\n            [allowFreeEntries]=\"false\"\n            [disabled]=\"\n              (baseVersions$ | async) === null || (baseVersions$ | async)?.data.length === 0\n            \"\n            [required]=\"true\"\n          >\n            <c8y-li\n              *c8yFor=\"\n                let baseVersion of baseVersions$;\n                loadMore: 'auto';\n                pipe: baseVersionsFilterPipe\n              \"\n              class=\"p-l-8 p-r-8 c8y-list__item--link\"\n              (click)=\"model.dependency = baseVersion\"\n              [active]=\"model.dependency === baseVersion\"\n            >\n              <c8y-highlight\n                [text]=\"baseVersion.c8y_Firmware.version || '--'\"\n                [pattern]=\"patchDependencyInput$ | async\"\n              ></c8y-highlight>\n            </c8y-li>\n          </c8y-typeahead>\n          <c8y-messages>\n            <c8y-message\n              name=\"notExisting\"\n              [text]=\"'Select one of the existing versions.' | translate\"\n            ></c8y-message>\n          </c8y-messages>\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label for=\"patchVersion\" translate>Patch</label>\n          <input\n            id=\"patchVersion\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            name=\"patchVersion\"\n            data-cy=\"add-firmware-patch-modal--patchVersion\"\n            [(ngModel)]=\"model.patchVersion\"\n            placeholder=\"{{ 'e.g.' | translate }} 1.0.0\"\n            required\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div class=\"legend form-block m-t-40\" translate>Patch 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        title=\"{{ 'Cancel' | translate }}\"\n        data-cy=\"add-firmware-patch-modal--cancel-btn\"\n        class=\"btn btn-default\"\n        type=\"button\"\n        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n        translate\n      >\n        Cancel\n      </button>\n      <button\n        title=\"{{ 'Add firmware patch' | translate }}\"\n        class=\"btn btn-primary\"\n        type=\"submit\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !firmwarePatchForm.form.valid ||\n          firmwarePatchForm.form.pristine ||\n          (!model.binary?.url && !model.binary?.file) ||\n          saving\n        \"\n        translate\n        c8yProductExperience\n        [actionName]=\"PRODUCT_EXPERIENCE.FIRMWARE.EVENTS.REPOSITORY\"\n        [actionData]=\"{\n          component: PRODUCT_EXPERIENCE.FIRMWARE.COMPONENTS.ADD_FIRMWAR_PATCH_MODAL,\n          result: PRODUCT_EXPERIENCE.FIRMWARE.RESULTS.ADD_FIRMWARE_PATCH\n        }\"\n      >\n        Add firmware patch\n      </button>\n    </div>\n  </form>\n</div>\n" }]
        }], ctorParameters: () => [{ type: i1.BsModalRef }, { type: i2.RepositoryService }, { type: i3.AlertService }], propDecorators: { saved: [{
                type: Output
            }], dropdown: [{
                type: ViewChild,
                args: ['dropdown', { static: false }]
            }], form: [{
                type: ViewChild,
                args: ['firmwarePatchForm', { static: false }]
            }] } });
//# sourceMappingURL=data:application/json;base64, 