import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AlertService, gettext, ValidationPattern } from '@c8y/ngx-components';
import { RepositoryService, RepositoryType } from '@c8y/ngx-components/repository/shared';
import { isUndefined, uniqBy } from 'lodash-es';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import * as i0 from "@angular/core";
import * as i1 from "@c8y/ngx-components/repository/shared";
import * as i2 from "ngx-bootstrap/modal";
import * as i3 from "@c8y/ngx-components";
import * as i4 from "@angular/common";
import * as i5 from "@angular/forms";
export class ConfigurationDetailComponent {
    constructor(repositoryService, bsModalRef, alert) {
        this.repositoryService = repositoryService;
        this.bsModalRef = bsModalRef;
        this.alert = alert;
        this.binary = {
            file: undefined,
            url: undefined
        };
        this.pattern = '';
        this.mo = {};
        this.saving = false;
        this.uploadChoice = 'uploadBinary';
        this.textForConfigurationUrlPopover = gettext(`Path for binaries can vary depending on device agent implementation, for example:
    /configuration/binaries/configuration1.bin
    https://configuration/binary/123
    ftp://configuration/binary/123.tar.gz
    Configurations with external URLs only work with the configuration typed devices (file-based configuration), not with devices with a legacy configuration.
  `);
        this.result = new Promise((resolve, reject) => {
            this._save = resolve;
            this._cancel = reject;
        });
        this.ValidationPattern = ValidationPattern;
    }
    async ngOnInit() {
        this.configs = await this.repositoryService.listRepositoryEntries(RepositoryType.CONFIGURATION);
        if (this.mo) {
            this.uploadChoice = this.binary.file ? 'uploadBinary' : 'uploadUrl';
            this.existingBinary = this.binary.file;
            this.configurationTypeMO = this.mo;
        }
        this.setPipe('');
        this.submitButtonTitle = this.mo.id
            ? gettext('Update configuration')
            : gettext('Add configuration');
    }
    cancel() {
        this.bsModalRef.hide();
        this._cancel();
    }
    setPipe(filterStr) {
        this.pattern = filterStr;
        this.filterPipe = pipe(map(data => uniqBy(data, 'configurationType')), map(data => {
            return data.filter(mo => mo.configurationType &&
                mo.configurationType.toLowerCase().indexOf(filterStr.toLowerCase()) > -1);
        }));
    }
    onFile(dropped) {
        this.configurationForm.form.markAsDirty();
        if (!isUndefined(dropped.url)) {
            this.binary = {
                url: dropped.url
            };
            return;
        }
        else if (dropped.droppedFiles) {
            this.binary = {
                file: dropped.droppedFiles[0].file
            };
            return;
        }
        else {
            this.binary = {
                file: undefined,
                url: undefined
            };
        }
    }
    async save() {
        try {
            this.saving = true;
            const { version, description, binary, deviceType } = this;
            if (this.existingBinary === this.binary.file) {
                binary.file = undefined;
            }
            await this.repositoryService.create({
                version,
                description,
                binary,
                deviceType,
                configurationType: this.configurationTypeMO?.configurationType
            }, RepositoryType.CONFIGURATION, this.mo);
            this.alert.success(this.mo.id ? gettext('Configuration updated.') : gettext('Configuration created.'));
            this.bsModalRef.hide();
            this._save();
        }
        catch (ex) {
            this.alert.addServerFailure(ex);
            this._cancel();
        }
        finally {
            this.saving = false;
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: ConfigurationDetailComponent, deps: [{ token: i1.RepositoryService }, { token: i2.BsModalRef }, { token: i3.AlertService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: ConfigurationDetailComponent, selector: "c8y-configuration-detail", viewQueries: [{ propertyName: "configurationForm", first: true, predicate: ["configurationForm"], descendants: true, static: true }], ngImport: i0, template: "<div class=\"viewport-modal\">\n  <div\n    class=\"modal-header dialog-header\"\n    id=\"configurationModalTitle\"\n  >\n    <i [c8yIcon]=\"'cogs'\"></i>\n    <h4\n      id=\"modal-title\"\n      translate\n      *ngIf=\"mo.id\"\n    >\n      Update configuration\n    </h4>\n    <h4\n      id=\"modal-title\"\n      translate\n      *ngIf=\"!mo.id\"\n    >\n      Add configuration\n    </h4>\n  </div>\n\n  <form\n    class=\"d-contents\"\n    #configurationForm=\"ngForm\"\n    (ngSubmit)=\"configurationForm.form.valid && save()\"\n  >\n    <div\n      class=\"modal-inner-scroll\"\n      id=\"modal-body\"\n    >\n      <div\n        class=\"modal-body\"\n        id=\"configurationModalDescription\"\n      >\n        <c8y-form-group>\n          <label translate>Name</label>\n          <input\n            class=\"form-control\"\n            placeholder=\"{{ 'e.g.' | translate }} hosts\"\n            name=\"version\"\n            type=\"text\"\n            autocomplete=\"off\"\n            required\n            maxlength=\"254\"\n            [(ngModel)]=\"version\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label translate>Device type</label>\n          <input\n            class=\"form-control\"\n            placeholder=\"{{ 'e.g.' | translate }} c8y_Linux\"\n            name=\"deviceType\"\n            type=\"text\"\n            autocomplete=\"off\"\n            maxlength=\"254\"\n            [(ngModel)]=\"deviceType\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label translate>Description</label>\n          <input\n            class=\"form-control\"\n            placeholder=\"{{ 'e.g. Host configuration' | translate }} c8y_Linux\"\n            name=\"description\"\n            type=\"text\"\n            autocomplete=\"off\"\n            maxlength=\"254\"\n            [(ngModel)]=\"description\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label translate>Configuration type</label>\n          <c8y-typeahead\n            placeholder=\"{{ 'e.g.' | translate }} ssh\"\n            name=\"confType\"\n            [(ngModel)]=\"configurationTypeMO\"\n            maxlength=\"254\"\n            (onSearch)=\"setPipe($event)\"\n            displayProperty=\"configurationType\"\n          >\n            <c8y-li\n              class=\"p-l-8 p-r-8 c8y-list__item--link\"\n              *c8yFor=\"let config of configs; pipe: filterPipe; notFound: notFoundTemplate\"\n              (click)=\"configurationTypeMO = config; setPipe('')\"\n              [active]=\"configurationTypeMO === config\"\n            >\n              <c8y-highlight\n                [text]=\"config.configurationType || '--'\"\n                [pattern]=\"pattern\"\n              ></c8y-highlight>\n            </c8y-li>\n            <ng-template #notFoundTemplate>\n              <c8y-li\n                class=\"bg-level-2 p-8\"\n                *ngIf=\"pattern.length > 0\"\n              >\n                <span translate>No match found.</span>\n                <button\n                  class=\"btn btn-primary btn-xs m-l-8\"\n                  title=\"{{ 'Add new`configuration type`' | translate }}\"\n                  type=\"button\"\n                  translate\n                >\n                  Add new`configuration type`\n                </button>\n              </c8y-li>\n            </ng-template>\n          </c8y-typeahead>\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div\n            class=\"legend form-block m-t-40\"\n            translate\n          >\n            Configuration file\n          </div>\n          <c8y-file-picker\n            [maxAllowedFiles]=\"1\"\n            (onFilesPicked)=\"onFile($event)\"\n            [uploadChoice]=\"uploadChoice\"\n            [fileUrl]=\"binary.url\"\n            [fileBinary]=\"binary.file\"\n            [fileUrlPopover]=\"textForConfigurationUrlPopover\"\n          ></c8y-file-picker>\n        </c8y-form-group>\n      </div>\n    </div>\n\n    <div class=\"modal-footer\">\n      <button\n        class=\"btn btn-default\"\n        title=\"{{ 'Cancel' | translate }}\"\n        type=\"button\"\n        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n      >\n        <span translate>Cancel</span>\n      </button>\n      <button\n        class=\"btn btn-primary\"\n        title=\"{{ submitButtonTitle | translate }}\"\n        type=\"submit\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !configurationForm.valid ||\n          configurationForm.pristine ||\n          (!binary?.url?.trim() && !binary?.file) ||\n          saving\n        \"\n      >\n        {{ submitButtonTitle | 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.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { 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: "pipe", type: i3.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: ConfigurationDetailComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-configuration-detail', template: "<div class=\"viewport-modal\">\n  <div\n    class=\"modal-header dialog-header\"\n    id=\"configurationModalTitle\"\n  >\n    <i [c8yIcon]=\"'cogs'\"></i>\n    <h4\n      id=\"modal-title\"\n      translate\n      *ngIf=\"mo.id\"\n    >\n      Update configuration\n    </h4>\n    <h4\n      id=\"modal-title\"\n      translate\n      *ngIf=\"!mo.id\"\n    >\n      Add configuration\n    </h4>\n  </div>\n\n  <form\n    class=\"d-contents\"\n    #configurationForm=\"ngForm\"\n    (ngSubmit)=\"configurationForm.form.valid && save()\"\n  >\n    <div\n      class=\"modal-inner-scroll\"\n      id=\"modal-body\"\n    >\n      <div\n        class=\"modal-body\"\n        id=\"configurationModalDescription\"\n      >\n        <c8y-form-group>\n          <label translate>Name</label>\n          <input\n            class=\"form-control\"\n            placeholder=\"{{ 'e.g.' | translate }} hosts\"\n            name=\"version\"\n            type=\"text\"\n            autocomplete=\"off\"\n            required\n            maxlength=\"254\"\n            [(ngModel)]=\"version\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label translate>Device type</label>\n          <input\n            class=\"form-control\"\n            placeholder=\"{{ 'e.g.' | translate }} c8y_Linux\"\n            name=\"deviceType\"\n            type=\"text\"\n            autocomplete=\"off\"\n            maxlength=\"254\"\n            [(ngModel)]=\"deviceType\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label translate>Description</label>\n          <input\n            class=\"form-control\"\n            placeholder=\"{{ 'e.g. Host configuration' | translate }} c8y_Linux\"\n            name=\"description\"\n            type=\"text\"\n            autocomplete=\"off\"\n            maxlength=\"254\"\n            [(ngModel)]=\"description\"\n            [pattern]=\"ValidationPattern.rules.noWhiteSpaceOnly.pattern\"\n          />\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <label translate>Configuration type</label>\n          <c8y-typeahead\n            placeholder=\"{{ 'e.g.' | translate }} ssh\"\n            name=\"confType\"\n            [(ngModel)]=\"configurationTypeMO\"\n            maxlength=\"254\"\n            (onSearch)=\"setPipe($event)\"\n            displayProperty=\"configurationType\"\n          >\n            <c8y-li\n              class=\"p-l-8 p-r-8 c8y-list__item--link\"\n              *c8yFor=\"let config of configs; pipe: filterPipe; notFound: notFoundTemplate\"\n              (click)=\"configurationTypeMO = config; setPipe('')\"\n              [active]=\"configurationTypeMO === config\"\n            >\n              <c8y-highlight\n                [text]=\"config.configurationType || '--'\"\n                [pattern]=\"pattern\"\n              ></c8y-highlight>\n            </c8y-li>\n            <ng-template #notFoundTemplate>\n              <c8y-li\n                class=\"bg-level-2 p-8\"\n                *ngIf=\"pattern.length > 0\"\n              >\n                <span translate>No match found.</span>\n                <button\n                  class=\"btn btn-primary btn-xs m-l-8\"\n                  title=\"{{ 'Add new`configuration type`' | translate }}\"\n                  type=\"button\"\n                  translate\n                >\n                  Add new`configuration type`\n                </button>\n              </c8y-li>\n            </ng-template>\n          </c8y-typeahead>\n        </c8y-form-group>\n\n        <c8y-form-group>\n          <div\n            class=\"legend form-block m-t-40\"\n            translate\n          >\n            Configuration file\n          </div>\n          <c8y-file-picker\n            [maxAllowedFiles]=\"1\"\n            (onFilesPicked)=\"onFile($event)\"\n            [uploadChoice]=\"uploadChoice\"\n            [fileUrl]=\"binary.url\"\n            [fileBinary]=\"binary.file\"\n            [fileUrlPopover]=\"textForConfigurationUrlPopover\"\n          ></c8y-file-picker>\n        </c8y-form-group>\n      </div>\n    </div>\n\n    <div class=\"modal-footer\">\n      <button\n        class=\"btn btn-default\"\n        title=\"{{ 'Cancel' | translate }}\"\n        type=\"button\"\n        (click)=\"cancel()\"\n        [disabled]=\"saving\"\n      >\n        <span translate>Cancel</span>\n      </button>\n      <button\n        class=\"btn btn-primary\"\n        title=\"{{ submitButtonTitle | translate }}\"\n        type=\"submit\"\n        [ngClass]=\"{ 'btn-pending': saving }\"\n        [disabled]=\"\n          !configurationForm.valid ||\n          configurationForm.pristine ||\n          (!binary?.url?.trim() && !binary?.file) ||\n          saving\n        \"\n      >\n        {{ submitButtonTitle | translate }}\n      </button>\n    </div>\n  </form>\n</div>\n" }]
        }], ctorParameters: () => [{ type: i1.RepositoryService }, { type: i2.BsModalRef }, { type: i3.AlertService }], propDecorators: { configurationForm: [{
                type: ViewChild,
                args: ['configurationForm', { static: true }]
            }] } });
//# sourceMappingURL=data:application/json;base64, 