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 { 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 AddSoftwareModalComponent {
    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,
            softwareType: undefined,
            binary: {
                file: undefined,
                url: undefined
            }
        };
        this.saving = false;
        this.softwarePreselected = false;
        this.textForSoftwareUrlPopover = gettext(`Path for binaries can vary depending on device agent implementation, for example:
    /software/binaries/software1.bin
    https://software/binary/123
    ftp://software/binary/123.tar.gz
  `);
    }
    ngOnInit() {
        this.setInitialState();
        this.loadSoftwares();
    }
    setInitialState() {
        if (this.model.selected) {
            this.softwarePreselected = true;
        }
    }
    loadSoftwares() {
        this.inputSubscription$ = this.onInput
            .pipe(tap(() => {
            if (!this.softwarePreselected) {
                this.model.description = null;
                if (this.form) {
                    this.form.form.get('description').reset();
                }
            }
        }), debounceTime(300), distinctUntilChanged(), switchMap(searchStr => this.getSoftwareResult(searchStr)))
            .subscribe(result => {
            this.softwaresResult = result;
        });
    }
    getSoftwareResult(searchStr) {
        return from(this.repositoryService.listRepositoryEntries(RepositoryType.SOFTWARE, {
            partialName: searchStr,
            skipLegacy: true
        }));
    }
    async save() {
        this.saving = true;
        this.repositoryService
            .create(this.model, RepositoryType.SOFTWARE)
            .then(savedSoftware => {
            this.successMsg();
            this.saving = false;
            this.saved.next(savedSoftware);
            this.cancel();
        })
            .catch(e => {
            this.saving = false;
            this.saved.error(e);
            this.cancel();
        });
    }
    successMsg() {
        const msg = gettext('Software 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
            };
        }
    }
    onSoftwareSelect(software) {
        assign(this.model, {
            selected: software,
            description: software.description,
            deviceType: get(software, 'c8y_Filter.type'),
            softwareType: software
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: AddSoftwareModalComponent, 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: AddSoftwareModalComponent, selector: "c8y-add-software-software-modal", outputs: { saved: "saved" }, viewQueries: [{ propertyName: "form", first: true, predicate: ["softwareForm"], descendants: true }], ngImport: i0, template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'c8y-tools'\"></i>\n    <div class=\"modal-title\" translate id=\"addSoftwareModalTitle\">Add software</div>\n  </div>\n  <div class=\"p-16 text-center separator-bottom\" *ngIf=\"!softwarePreselected\">\n    <p class=\"text-medium text-16\" translate>Select or create new software</p>\n  </div>\n  <form\n    class=\"d-contents\"\n    autocomplete=\"off\"\n    #softwareForm=\"ngForm\"\n    (ngSubmit)=\"softwareForm.form.valid && save()\"\n  >\n    <div class=\"modal-inner-scroll\">\n      <div class=\"modal-body\" id=\"addSoftwareModalDescription\">\n        <div [hidden]=\"softwarePreselected\">\n          <c8y-form-group>\n            <label for=\"softwareName\" translate>Software</label>\n            <c8y-typeahead\n              [(ngModel)]=\"model.selected\"\n              name=\"softwareName\"\n              placeholder=\"{{ 'Select or enter' | translate }}\"\n              (onSearch)=\"onInput.next($event)\"\n              [required]=\"true\"\n            >\n              <c8y-li\n                *c8yFor=\"\n                  let software of softwaresResult;\n                  loadMore: 'auto';\n                  notFound: notFoundTemplate\n                \"\n                class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                (click)=\"onSoftwareSelect(software)\"\n                [active]=\"model.selected === software\"\n              >\n                <c8y-highlight\n                  [text]=\"software.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`software`' | translate }}\"\n                  >\n                    {{ 'Add new`software`' | translate }}\n                  </button>\n                </c8y-li>\n              </ng-template>\n            </c8y-typeahead>\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label for=\"softwareDescription\" translate>Description</label>\n            <input\n              id=\"softwareDescription\"\n              class=\"form-control\"\n              autocomplete=\"off\"\n              name=\"description\"\n              [(ngModel)]=\"model.description\"\n              placeholder=\"{{ 'e.g. Cloud connectivity software' | translate }}\"\n              [disabled]=\"model.selected?.id\"\n              [required]=\"true\"\n            />\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label class=\"control-label\" for=\"softwareDeviceTypeFilter\">\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 software 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                placement=\"right\"\n                triggers=\"focus\"\n                container=\"body\"\n              ></button>\n            </label>\n            <input\n              id=\"softwareDeviceTypeFilter\"\n              class=\"form-control\"\n              name=\"softwareDeviceTypeFilter\"\n              [(ngModel)]=\"model.deviceType\"\n              placeholder=\"{{ 'e.g.' | translate }} c8y_Linux\"\n              [disabled]=\"model.selected?.id\"\n            />\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label for=\"softwareType\" translate>Software type</label>\n            <c8y-software-type\n              name=\"softwareType\"\n              [(ngModel)]=\"model.softwareType\"\n              [disabled]=\"model.selected?.id\"\n            ></c8y-software-type>\n          </c8y-form-group>\n        </div>\n\n        <c8y-form-group>\n          <label for=\"softwareVersion\" translate>Version</label>\n          <input\n            id=\"softwareVersion\"\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          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div class=\"legend form-block m-t-40\" translate>Software file</div>\n          <c8y-file-picker\n            [maxAllowedFiles]=\"1\"\n            (onFilesPicked)=\"onFile($event)\"\n            [fileUrlPopover]=\"textForSoftwareUrlPopover\"\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        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n      >\n        {{ 'Cancel' | translate }}\n      </button>\n\n      <button\n        class=\"btn btn-primary\"\n        type=\"submit\"\n        title=\"{{ 'Add software' | translate }}\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !softwareForm.form.valid ||\n          softwareForm.form.pristine ||\n          saving ||\n          (!model.binary?.url && !model.binary?.file)\n        \"\n        c8yProductExperience\n        [actionName]=\"PRODUCT_EXPERIENCE.SOFTWARE.EVENTS.REPOSITORY\"\n        [actionData]=\"{\n          component: PRODUCT_EXPERIENCE.SOFTWARE.COMPONENTS.ADD_SOFTWARE_MODAL,\n          result:\n            softwarePreselected || model.selected?.id\n              ? PRODUCT_EXPERIENCE.SOFTWARE.RESULTS.ADD_SOFTWARE_VERSION\n              : PRODUCT_EXPERIENCE.SOFTWARE.RESULTS.ADD_SOFTWARE\n        }\"\n      >\n        {{ 'Add software' | translate }}\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.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: "component", type: i2.SoftwareTypeComponent, selector: "c8y-software-type", inputs: ["softwareTypeMO", "disabled", "style", "required", "placeholder", "emitResultsOnly", "showBtnInNotFoundMessage", "allowFreeEntries", "showClearSelectionOption", "clearSelectionOptionLabel", "presetSoftwareTypes"], outputs: ["onSelectSoftware"] }, { 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: AddSoftwareModalComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-add-software-software-modal', template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'c8y-tools'\"></i>\n    <div class=\"modal-title\" translate id=\"addSoftwareModalTitle\">Add software</div>\n  </div>\n  <div class=\"p-16 text-center separator-bottom\" *ngIf=\"!softwarePreselected\">\n    <p class=\"text-medium text-16\" translate>Select or create new software</p>\n  </div>\n  <form\n    class=\"d-contents\"\n    autocomplete=\"off\"\n    #softwareForm=\"ngForm\"\n    (ngSubmit)=\"softwareForm.form.valid && save()\"\n  >\n    <div class=\"modal-inner-scroll\">\n      <div class=\"modal-body\" id=\"addSoftwareModalDescription\">\n        <div [hidden]=\"softwarePreselected\">\n          <c8y-form-group>\n            <label for=\"softwareName\" translate>Software</label>\n            <c8y-typeahead\n              [(ngModel)]=\"model.selected\"\n              name=\"softwareName\"\n              placeholder=\"{{ 'Select or enter' | translate }}\"\n              (onSearch)=\"onInput.next($event)\"\n              [required]=\"true\"\n            >\n              <c8y-li\n                *c8yFor=\"\n                  let software of softwaresResult;\n                  loadMore: 'auto';\n                  notFound: notFoundTemplate\n                \"\n                class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                (click)=\"onSoftwareSelect(software)\"\n                [active]=\"model.selected === software\"\n              >\n                <c8y-highlight\n                  [text]=\"software.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`software`' | translate }}\"\n                  >\n                    {{ 'Add new`software`' | translate }}\n                  </button>\n                </c8y-li>\n              </ng-template>\n            </c8y-typeahead>\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label for=\"softwareDescription\" translate>Description</label>\n            <input\n              id=\"softwareDescription\"\n              class=\"form-control\"\n              autocomplete=\"off\"\n              name=\"description\"\n              [(ngModel)]=\"model.description\"\n              placeholder=\"{{ 'e.g. Cloud connectivity software' | translate }}\"\n              [disabled]=\"model.selected?.id\"\n              [required]=\"true\"\n            />\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label class=\"control-label\" for=\"softwareDeviceTypeFilter\">\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 software 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                placement=\"right\"\n                triggers=\"focus\"\n                container=\"body\"\n              ></button>\n            </label>\n            <input\n              id=\"softwareDeviceTypeFilter\"\n              class=\"form-control\"\n              name=\"softwareDeviceTypeFilter\"\n              [(ngModel)]=\"model.deviceType\"\n              placeholder=\"{{ 'e.g.' | translate }} c8y_Linux\"\n              [disabled]=\"model.selected?.id\"\n            />\n          </c8y-form-group>\n\n          <c8y-form-group>\n            <label for=\"softwareType\" translate>Software type</label>\n            <c8y-software-type\n              name=\"softwareType\"\n              [(ngModel)]=\"model.softwareType\"\n              [disabled]=\"model.selected?.id\"\n            ></c8y-software-type>\n          </c8y-form-group>\n        </div>\n\n        <c8y-form-group>\n          <label for=\"softwareVersion\" translate>Version</label>\n          <input\n            id=\"softwareVersion\"\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          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div class=\"legend form-block m-t-40\" translate>Software file</div>\n          <c8y-file-picker\n            [maxAllowedFiles]=\"1\"\n            (onFilesPicked)=\"onFile($event)\"\n            [fileUrlPopover]=\"textForSoftwareUrlPopover\"\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        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n      >\n        {{ 'Cancel' | translate }}\n      </button>\n\n      <button\n        class=\"btn btn-primary\"\n        type=\"submit\"\n        title=\"{{ 'Add software' | translate }}\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !softwareForm.form.valid ||\n          softwareForm.form.pristine ||\n          saving ||\n          (!model.binary?.url && !model.binary?.file)\n        \"\n        c8yProductExperience\n        [actionName]=\"PRODUCT_EXPERIENCE.SOFTWARE.EVENTS.REPOSITORY\"\n        [actionData]=\"{\n          component: PRODUCT_EXPERIENCE.SOFTWARE.COMPONENTS.ADD_SOFTWARE_MODAL,\n          result:\n            softwarePreselected || model.selected?.id\n              ? PRODUCT_EXPERIENCE.SOFTWARE.RESULTS.ADD_SOFTWARE_VERSION\n              : PRODUCT_EXPERIENCE.SOFTWARE.RESULTS.ADD_SOFTWARE\n        }\"\n      >\n        {{ 'Add software' | translate }}\n      </button>\n    </div>\n  </form>\n</div>\n" }]
        }], ctorParameters: () => [{ type: i1.BsModalRef }, { type: i2.RepositoryService }, { type: i3.AlertService }], propDecorators: { form: [{
                type: ViewChild,
                args: ['softwareForm', { static: false }]
            }], saved: [{
                type: Output
            }] } });
//# sourceMappingURL=data:application/json;base64, 