import { __awaiter, __decorate } from "tslib";
import { Router, ActivatedRoute } from '@angular/router';
import { Component } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { TranslateService } from '@ngx-translate/core';
import { distinctUntilChanged, tap, debounceTime, switchMap, shareReplay, map } from 'rxjs/operators';
import { BehaviorSubject, combineLatest, from } from 'rxjs';
import { ModalService, gettext, Status, AlertService, memoize } from '@c8y/ngx-components';
import { RepositoryService } from '../repository.service';
import { RepositoryType } from '../repository.model';
import { AddFirmwareModalComponent } from './add-firmware-modal.component';
import { AddFirmwarePatchModalComponent } from './add-firmware-patch-modal.component';
import { property, get } from 'lodash-es';
export class FirmwareListComponent {
    constructor(repositoryService, modalService, bsModalService, translateService, alertService, router, activatedRoute) {
        this.repositoryService = repositoryService;
        this.modalService = modalService;
        this.bsModalService = bsModalService;
        this.translateService = translateService;
        this.alertService = alertService;
        this.router = router;
        this.activatedRoute = activatedRoute;
        this.textFilter$ = new BehaviorSubject('');
        this.reload$ = new BehaviorSubject(null);
        this.reloading = false;
        this.firmwares$ = combineLatest(this.textFilter$.pipe(debounceTime(400), distinctUntilChanged()), this.reload$).pipe(tap(() => {
            this.reloading = true;
        }), switchMap(([text]) => this.getFirmwares(text)), tap(() => {
            this.reloading = false;
        }), shareReplay(1));
        this.canAddFirmwarePatch$ = from(this.repositoryService.listRepositoryEntries(RepositoryType.FIRMWARE, { skipLegacy: true })).pipe(map(({ data }) => data.length > 0));
        this.isLegacy = this.repositoryService.isLegacyEntry.bind(this.repositoryService);
        this.DEVICE_TYPE_NOT_AVAILABLE = gettext('No device type available');
    }
    getFirmwares(partialText) {
        const properties = ['name', 'description', 'c8y_Filter.type'];
        const partialTextFilter = { partialText, properties };
        return this.repositoryService.listRepositoryEntries(RepositoryType.FIRMWARE, {
            partialTextFilter
        });
    }
    addFirmware() {
        const config = { class: 'modal-sm', ignoreBackdropClick: true };
        const modalRef = this.bsModalService.show(AddFirmwareModalComponent, config);
        modalRef.content.saved.subscribe(savedFirmware => this.editFirmware(savedFirmware));
    }
    addFirmwarePatch() {
        const config = { class: 'modal-sm', ignoreBackdropClick: true };
        const modalRef = this.bsModalService.show(AddFirmwarePatchModalComponent, config);
        modalRef.content.saved.subscribe(savedFirmware => this.editFirmware(savedFirmware));
    }
    editFirmware(firmware) {
        this.router.navigate([firmware.id], { relativeTo: this.activatedRoute });
    }
    deleteFirmware(firmware) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const title = gettext('Delete firmware');
                const body = `
        ${this.translateService.instant(gettext('You are about to delete firmware "{{ name }}" with all its versions and patches.'), { name: firmware.name })}
        ${this.translateService.instant(gettext('This operation is irreversible.'))}
        ${this.translateService.instant(gettext('Do you want to proceed?'))}
      `;
                const labels = {
                    ok: gettext('Delete')
                };
                yield this.modalService.confirm(title, body, Status.DANGER, labels);
                yield this.repositoryService.delete(firmware);
                this.alertService.success(gettext('Firmware deleted.'));
                this.reload$.next();
            }
            catch (ex) {
                // only if not cancel from modal
                if (ex) {
                    this.alertService.addServerFailure(ex);
                }
            }
        });
    }
    getBaseVersionsCount$(firmware) {
        return this.firmwares$.pipe(switchMap(() => this.repositoryService.getBaseVersionsCount$(firmware)), shareReplay(1));
    }
    getDeviceTypeTitle(firmware) {
        return get(firmware, 'c8y_Filter.type', this.translateService.instant(this.DEVICE_TYPE_NOT_AVAILABLE));
    }
}
FirmwareListComponent.decorators = [
    { type: Component, args: [{
                selector: 'c8y-firmware-list',
                template: "<c8y-title>\n  {{ 'Firmware repository' | translate }}\n</c8y-title>\n\n<c8y-action-bar-item [placement]=\"'left'\" itemClass=\"navbar-form\">\n  <div class=\"input-group input-group-search\">\n    <input class=\"form-control\"\n      type=\"search\"\n      title=\"{{ 'Filter firmware\u2026' | translate }}\"\n      placeholder=\"{{ 'Filter firmware\u2026' | translate }}\"\n      [ngModel]=\"textFilter$ | async\"\n      (ngModelChange)=\"textFilter$.next($event)\"\n    />\n    <span class=\"input-group-addon\">\n      <i\n        c8yIcon=\"search\"\n        *ngIf=\"(textFilter$ | async).length === 0\"\n      ></i>\n      <i class=\"text-muted\"\n        c8yIcon=\"times\"\n        *ngIf=\"(textFilter$ | async).length > 0\"\n        (click)=\"textFilter$.next('')\"\n      ></i>\n    </span>\n  </div>\n</c8y-action-bar-item>\n\n<c8y-action-bar-item [placement]=\"'right'\">\n  <button class=\"btn btn-link\"\n    title=\"{{ 'Add firmware' | translate }}\"\n    (click)=\"addFirmware()\"\n  >\n    <i c8yIcon=\"plus-circle\"></i>\n    {{ 'Add firmware' | translate }}\n  </button>\n</c8y-action-bar-item>\n\n<c8y-action-bar-item [placement]=\"'right'\">\n  <button class=\"btn btn-link\"\n    *ngIf=\"canAddFirmwarePatch$ | async\"\n    title=\"{{ 'Add firmware patch' | translate }}\"\n    (click)=\"addFirmwarePatch()\"\n  >\n    <i c8yIcon=\"plus-circle\"></i>\n    {{ 'Add firmware patch' | translate }}\n  </button>\n</c8y-action-bar-item>\n\n<c8y-action-bar-item [placement]=\"'right'\">\n  <button class=\"btn btn-link\"\n    title=\"{{ 'Reload' | translate }}\"\n    (click)=\"reload$.next()\"\n  >\n    <i c8yIcon=\"refresh\"\n      [ngClass]=\"{ 'icon-spin': reloading }\"\n    ></i>\n    {{ 'Reload' | translate }}\n  </button>\n</c8y-action-bar-item>\n\n<!-- empty state-->\n<div class=\"c8y-empty-state text-center\"\n  *ngIf=\"(firmwares$ | async)?.data.length === 0 && (textFilter$ | async)?.length === 0\"\n>\n  <h1 class=\"c8y-icon-duocolor\"\n    c8yIcon=\"c8y-firmware\"\n  ></h1>\n  <h3 translate>\n    No firmwares to display.\n  </h3>\n  <p translate>\n    Add a new firmware by clicking below.\n  </p>\n  <p>\n    <button class=\"btn btn-primary\"\n      title=\"{{ 'Add firmware' | translate }}\"\n      (click)=\"addFirmware()\"\n      translate\n    >\n      Add firmware\n    </button>\n  </p>\n</div>\n\n<!-- no results empty state -->\n<div class=\"c8y-empty-state\"\n  *ngIf=\"(firmwares$ | async)?.data.length === 0 && (textFilter$ | async)?.length > 0\"\n  >\n  <h1 class=\"c8y-icon-duocolor\"\n    c8yIcon=\"search\"></h1>\n  <h3 translate>\n    No results to display.\n  </h3>\n  <p translate>\n    Refine your search terms or check your spelling.\n  </p>\n</div>\n\n<c8y-list-group class=\"m-b-24\"\n  *ngIf=\"(firmwares$ | async)?.data.length > 0\"\n  [ngClass]=\"{ 'dd-low': (firmwares$ | async)?.data.length < 10 }\"\n\n>\n  <c8y-li class=\"page-sticky-header c8y-list__item--empty-actions hidden-xs\">\n    <c8y-li-icon>\n      <i class=\"p-l-24\"></i>\n    </c8y-li-icon>\n    <c8y-li-body class=\"content-flex-60\">\n      <div class=\"col-3\">\n        {{'Firmware' | translate}}\n      </div>\n      <div class=\"col-4\">\n        {{'Description' | translate}}\n      </div>\n      <div class=\"col-3\">\n        {{'Device type' | translate}}\n      </div>\n      <div class=\"col-2\">\n        {{'Versions' | translate}}\n      </div>\n    </c8y-li-body>\n  </c8y-li>\n\n  <c8y-li *c8yFor=\"let firmware of firmwares$ | async; let i = index; loadMore: 'auto'\">\n    <c8y-li-icon icon=\"c8y-firmware\"></c8y-li-icon>\n    <c8y-li-body class=\"content-flex-60\">\n      <button class=\"btn-clean col-3\"\n        (click)=\"editFirmware(firmware)\"\n      >\n        <span class=\"text-truncate\"\n          title=\"{{ firmware.name }}\"\n        >\n          <c8y-highlight\n            [text]=\"firmware.name || '-'\"\n            elementClass=\"text-info\"\n            [pattern]=\"textFilter$ | async\"\n          ></c8y-highlight>\n        </span>\n      </button>\n      <div class=\"col-4\">\n        <p class=\"text-truncate\"\n          title=\"{{ firmware.description }}\"\n        >\n          <span class=\"text-label-small m-r-4 visible-xs-inline\">\n            {{'Description' | translate }}\n          </span>\n          <span *ngIf=\"firmware.description; else emptyDescription\">\n            <c8y-highlight\n              [text]=\"firmware.description || '-'\"\n              elementClass=\"text-info\"\n              [pattern]=\"textFilter$ | async\"\n            ></c8y-highlight>\n          </span>\n        </p>\n        <ng-template #emptyDescription>\n          <small class=\"text-muted\">\n            <em>{{ 'No description' | translate }}</em>\n          </small>\n        </ng-template>\n      </div>\n      <div class=\"col-3\">\n        <div class=\"text-truncate\">\n          <span class=\"text-label-small m-r-4 visible-xs-inline\" translate>\n            Device type\n          </span>\n          <span\n            *ngIf=\"firmware.c8y_Filter?.type; else emptyText\"\n            title=\"{{ firmware.c8y_Filter?.type }}\"\n          >\n            <c8y-highlight\n              [text]=\"firmware.c8y_Filter?.type || '-'\"\n              elementClass=\"text-info\"\n              [pattern]=\"textFilter$ | async\"\n            ></c8y-highlight>\n          </span>\n          <ng-template #emptyText>\n            <small class=\"text-muted\">\n              <em>{{ 'Undefined' | translate }}</em>\n            </small>\n          </ng-template>\n        </div>\n      </div>\n      <div class=\"col-2\">\n        <span class=\"label label-warning flex-item-right-sm\"\n          *ngIf=\"isLegacy(firmware)\"\n          >\n          <span translate>\n            Legacy\n          </span>\n        </span>\n\n        <span *ngIf=\"!isLegacy(firmware)\">\n          <span *ngIf=\"(getBaseVersionsCount$(firmware) | async) === null\">\n            <span class=\"label label-info flex-item-right-sm\">\n              <i c8yIcon=\"circle-o-notch\" class=\"icon-spin\"></i>\n            </span>\n          </span>\n          <span *ngIf=\"(getBaseVersionsCount$(firmware) | async) !== null\">\n            <span [ngPlural]=\"getBaseVersionsCount$(firmware) | async\">\n              <ng-template ngPluralCase=\"=0\">\n                <span class=\"label label-default flex-item-right-sm\">\n                  <span translate>\n                    No versions\n                  </span>\n                </span>\n              </ng-template>\n              <ng-template ngPluralCase=\"=1\">\n                <span class=\"label label-info flex-item-right-sm\">\n                  <span translate>\n                    1 version\n                  </span>\n                </span>\n              </ng-template>\n              <ng-template ngPluralCase=\"other\">\n                <span class=\"label label-info flex-item-right-sm\">\n                  <span\n                    ngNonBindable\n                    translate\n                    [translateParams]=\"{ count: getBaseVersionsCount$(firmware) | async }\"\n                  >\n                    {{ count }} versions\n                  </span>\n                </span>\n              </ng-template>\n            </span>\n          </span>\n        </span>\n      </div>\n    </c8y-li-body>\n\n    <c8y-li-action\n      (click)=\"editFirmware(firmware)\"\n      icon=\"pencil\"\n    >\n      {{ 'Edit' | translate }}\n    </c8y-li-action>\n\n    <c8y-li-action\n      (click)=\"deleteFirmware(firmware)\"\n      icon=\"trash\"\n    >\n      {{ 'Delete' | translate }}\n    </c8y-li-action>\n  </c8y-li>\n</c8y-list-group>\n"
            },] }
];
FirmwareListComponent.ctorParameters = () => [
    { type: RepositoryService },
    { type: ModalService },
    { type: BsModalService },
    { type: TranslateService },
    { type: AlertService },
    { type: Router },
    { type: ActivatedRoute }
];
__decorate([
    memoize(property('id'))
], FirmwareListComponent.prototype, "getBaseVersionsCount$", null);
//# sourceMappingURL=data:application/json;base64, 