import { __awaiter } from "tslib";
import { Component } from '@angular/core';
import { gettext } from '@c8y/ngx-components';
import { RepositoryService, RepositoryType } from '@c8y/ngx-components/repository';
import { TranslateService } from '@ngx-translate/core';
import { get, isEqual, uniqWith } from 'lodash-es';
import { BehaviorSubject, combineLatest, from } from 'rxjs';
import { debounceTime, distinctUntilChanged, shareReplay, switchMap } from 'rxjs/operators';
import { BaseStepperComponent } from '@c8y/ngx-components/operations/bulk-operation-stepper';
import { BulkOperationsService } from '@c8y/ngx-components/operations/bulk-operations-service';
export class StepperBulkTypeConfigurationComponent extends BaseStepperComponent {
    constructor(bulkOperationService, repositoryService, translate) {
        super();
        this.bulkOperationService = bulkOperationService;
        this.repositoryService = repositoryService;
        this.translate = translate;
        this.NO_DEVICE_TYPE_AVAILABLE = gettext('Undefined`device type`');
        this.elementCount = 0;
        this.DD_LOW_COUNT = 10;
        this.textFilter$ = new BehaviorSubject('');
        this.configType$ = new BehaviorSubject('');
        this.configTypes = [];
        this.selectedConfigType = { name: '' };
        this.configurations$ = combineLatest(this.textFilter$, this.configType$).pipe(switchMap(([name, configType]) => this.getConfiguration(name, configType)), shareReplay(1));
        this.DD_LOW_COUNT = this.bulkOperationService.DD_LOW_COUNT;
        this.loadConfigurationTypes();
    }
    loadConfigurationTypes() {
        this.configTypeSubscription = this.configType$
            .pipe(debounceTime(300), distinctUntilChanged(), switchMap(searchStr => {
            const query = { configurationType: `*${searchStr}*` };
            return from(this.repositoryService.listRepositoryEntries(RepositoryType.CONFIGURATION, { query }));
        }))
            .subscribe(result => {
            const { data } = result;
            this.configTypes = uniqWith(data.map(val => ({ name: val.configurationType })), isEqual);
        });
    }
    ngOnDestroy() {
        this.configTypeSubscription.unsubscribe();
    }
    selectConfiguration(configuration) {
        this.selectedConfiguration = configuration;
    }
    goToSecondStep($event) {
        $event.stepper.next();
        this.getConfigBinary();
        this.deviceTypes = this.selectedConfiguration.deviceType;
    }
    getConfigBinary() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.selectedConfiguration.url) {
                this.selectedConfiguration.binary = yield this.repositoryService.getBinaryText(this.selectedConfiguration.url, { allowExternal: true, noAlerts: true });
            }
        });
    }
    getDeviceTypeTitle(configuration) {
        return get(configuration, 'deviceType', this.translate.instant(this.NO_DEVICE_TYPE_AVAILABLE));
    }
    retrieveOperationPrototype() {
        const configuration = {
            type: this.selectedConfiguration.configurationType,
            url: this.selectedConfiguration.url
        };
        return {
            name: gettext('Configuration update'),
            description: get(this.selectedConfiguration, 'name'),
            prototype: {
                description: `Update configuration to: ${this.selectedConfiguration.name}.`,
                c8y_DownloadConfigFile: configuration
            }
        };
    }
    getConfiguration(name, configurationType) {
        const query = name ? { name: `*${name}*` } : {};
        if (configurationType) {
            query.__or = [{ configurationType }, { __not: { __has: `configurationType` } }];
        }
        return this.repositoryService.listRepositoryEntries(RepositoryType.CONFIGURATION, { query });
    }
}
StepperBulkTypeConfigurationComponent.decorators = [
    { type: Component, args: [{
                selector: 'c8y-stepper-bulk-type-configuration',
                template: "<c8y-bulk-operation-stepper>\n  <ng-container\n    *customStep=\"\n      'Select configuration' | translate;\n      completed: !!selectedConfiguration;\n      buttonsDisabled: !selectedConfiguration;\n      onNext: goToSecondStep.bind(this)\"\n  >\n    <div class=\"card-block p-t-0 overflow-visible flex-no-shrink separator-bottom col-xs-12\">\n      <div class=\"row p-b-16\">\n        <div class=\"col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3\">\n          <h4 class=\"text-center m-b-16\">{{ 'Select configuration' | translate }}</h4>\n          <div class=\"row\">\n            <div class=\"col-md-6\">\n              <div class=\"input-group input-group-search\">\n                <input\n                  type=\"search\"\n                  class=\"form-control\"\n                  title=\"{{ 'Filter\u2026' | translate }}\"\n                  placeholder=\"{{ 'Filter\u2026' | translate }}\"\n                  [ngModel]=\"textFilter$ | async\"\n                  (ngModelChange)=\"textFilter$.next($event)\"\n                />\n                <span class=\"input-group-addon\">\n                  <i c8yIcon=\"filter\" *ngIf=\"(textFilter$ | async).length === 0\"></i>\n                  <i\n                    c8yIcon=\"times\"\n                    class=\"text-muted\"\n                    *ngIf=\"(textFilter$ | async).length > 0\"\n                    (click)=\"textFilter$.next('')\"\n                  ></i>\n                </span>\n              </div>\n            </div>\n            <div class=\"col-xs-12 p-b-8 visible-xs visible-sm\"></div>\n            <div class=\"col-md-6\">\n              <c8y-form-group class=\"m-0\">\n                <c8y-typeahead\n                  name=\"configType\"\n                  [(ngModel)]=\"selectedConfigType\"\n                  placeholder=\"{{ 'Type to filter configuration types\u2026' | translate }}\"\n                  (onSearch)=\"configType$.next($event)\"\n                >\n                  <c8y-li\n                    class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                    (click)=\"selectedConfigType = { name: '' }; configType$.next('')\"\n                  >\n                    <span>{{ 'All configuration types' | translate }}</span>\n                  </c8y-li>\n                  <c8y-li\n                    *ngFor=\"let configType of configTypes\"\n                    class=\"p-l-8 p-r-8 c8y-list__item--link\"\n                    (click)=\"selectedConfigType = configType; configType$.next(configType.name)\"\n                    [active]=\"selectedConfigType === configType\"\n                  >\n                    <c8y-highlight\n                      [text]=\"configType.name\"\n                      [pattern]=\"configType$ | async\"\n                    ></c8y-highlight>\n                  </c8y-li>\n                </c8y-typeahead>\n              </c8y-form-group>\n            </div>\n          </div>\n        </div>\n      </div>\n    </div>\n    <div class=\"col-xs-12 flex-grow no-gutter\">\n      <div class=\"card-inner-scroll fit-h\">\n        <div class=\"card-block p-t-0 p-b-0\">\n          <c8y-list-group [ngClass]=\"{ 'dd-low': elementCount < DD_LOW_COUNT }\">\n            <c8y-li #listItem *c8yFor=\"let configuration of configurations$ | async\">\n              <c8y-li-radio (onSelect)=\"selectConfiguration(configuration)\"></c8y-li-radio>\n              <c8y-li-icon icon=\"gears\"></c8y-li-icon>\n              <c8y-li-body class=\"content-flex-60\">\n                <div class=\"col-5\">\n                  <div class=\"text-truncate\" title=\"{{ configuration.name || '-' }}\">\n                    <c8y-highlight\n                      [text]=\"configuration.name || '-'\"\n                      [pattern]=\"textFilter$ | async\"\n                    ></c8y-highlight>\n                  </div>\n                </div>\n                <div class=\"col-4\">\n                  <div\n                    class=\"text-truncate\"\n                    title=\"{{ 'Device type' | translate }}: {{ getDeviceTypeTitle(configuration) }}\"\n                  >\n                    <span translate class=\"text-label-small m-r-4\">Device type</span>\n                    {{ configuration.deviceType }}\n                    <em class=\"text-muted\" *ngIf=\"!configuration.deviceType\">\n                      {{ 'Undefined`device type`' | translate }}\n                    </em>\n                  </div>\n                </div>\n                <div class=\"col-3\">\n                  <span\n                    class=\"label label-info\"\n                    *ngIf=\"configuration.configurationType\"\n                    title=\"{{ 'Configuration type' | translate }}: {{\n                      configuration.configurationType\n                    }}\"\n                  >\n                    <c8y-highlight\n                      [text]=\"configuration.configurationType\"\n                      elementClass=\"text-gray-lighter\"\n                      [pattern]=\"configType$ | async\"\n                    ></c8y-highlight>\n                  </span>\n                  <span\n                    class=\"label label-default\"\n                    *ngIf=\"!configuration.configurationType\"\n                    title=\"{{ 'Configuration type' | translate }}: {{ 'Undefined' | translate }}\"\n                  >\n                    {{ 'Undefined' | translate }}\n                  </span>\n                </div>\n              </c8y-li-body>\n            </c8y-li>\n          </c8y-list-group>\n        </div>\n      </div>\n    </div>\n  </ng-container>\n  <ng-container *customStep=\"'Preview configuration' | translate\">\n    <div class=\"d-contents\">\n      <div class=\"card-block p-t-0 flex-no-shrink separator-bottom\">\n        <div class=\"row\">\n          <div class=\"col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3\">\n            <h4 class=\"text-center m-b-16\">\n              {{ 'Preview configuration' | translate }}\n            </h4>\n            <div class=\"row no-gutter\">\n              <div class=\"col-xs-6\">\n                <div class=\"text-right text-truncate\" title=\"{{ selectedConfiguration?.name }}\">\n                  <strong>{{ selectedConfiguration?.name }}</strong>\n                </div>\n                <span class=\"label label-primary\" *ngIf=\"selectedConfiguration?.configurationType\">\n                  {{ selectedConfiguration.configurationType }}\n                </span>\n                <span class=\"label label-default\" *ngIf=\"!selectedConfiguration?.configurationType\">\n                  {{ 'Undefined' | translate }}\n                </span>\n              </div>\n              <div class=\"col-xs-6 text-right\">\n                <div class=\"text-truncate\" title=\"{{ 'Device type' | translate }}: {{ getDeviceTypeTitle(selectedConfiguration) }}\">\n                  <span translate class=\"text-label-small m-r-4\">\n                    Device type\n                  </span>\n                  {{ selectedConfiguration?.deviceType }}\n                  <em class=\"text-muted\" *ngIf=\"!selectedConfiguration?.deviceType\" translate>\n                    Undefined`device type`\n                  </em>\n                </div>\n                <p>\n                  <span translate class=\"text-label-small m-r-4\">Updated</span>\n                  <small>{{ selectedConfiguration?.lastUpdated | c8yDate }}</small>\n                </p>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n      <div class=\"col-xs-12 flex-grow no-gutter\">\n        <div class=\"card-inner-scroll fit-h\">\n          <div class=\"card-block p-t-0\">\n            <div class=\"row\">\n              <div class=\"col-md-8 col-md-offset-2\">\n                <div class=\"legend form-block\" translate>Preview</div>\n                <div\n                  class=\"c8y-empty-state text-left\"\n                  *ngIf=\"!this.selectedConfiguration?.binary; else binaryPreview\"\n                >\n                  <h1 [c8yIcon]=\"'file-code-o'\"></h1>\n                  <p>\n                    <strong translate>No preview available.</strong><br />\n                    <small translate>Could not fetch the file.</small>\n                  </p>\n                </div>\n                <ng-template #binaryPreview>\n                  <pre\n                    style=\"min-height: 98px;\"\n                  ><code>{{ this.selectedConfiguration?.binary }}</code></pre>\n                </ng-template>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n    </div>\n  </ng-container>\n</c8y-bulk-operation-stepper>\n"
            },] }
];
StepperBulkTypeConfigurationComponent.ctorParameters = () => [
    { type: BulkOperationsService },
    { type: RepositoryService },
    { type: TranslateService }
];
//# sourceMappingURL=data:application/json;base64, 