import { __awaiter, __decorate } from "tslib";
import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { InventoryService } from '@c8y/client';
import { AlertService, gettext, memoize, ModalService, Status } from '@c8y/ngx-components';
import { TranslateService } from '@ngx-translate/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BehaviorSubject, from, merge, Subject } from 'rxjs';
import { distinctUntilKeyChanged, map, shareReplay, switchMap, take, takeUntil, tap, withLatestFrom } from 'rxjs/operators';
import { RepositoryService } from '../repository.service';
import { AddSoftwareModalComponent } from './add-software-modal.component';
import { SoftwareTypeComponent } from './software-type.component';
export class SoftwareDetailsComponent {
    constructor(activatedRoute, inventoryService, repositoryService, alertService, translateService, modalService, bsModalService) {
        this.activatedRoute = activatedRoute;
        this.inventoryService = inventoryService;
        this.repositoryService = repositoryService;
        this.alertService = alertService;
        this.translateService = translateService;
        this.modalService = modalService;
        this.bsModalService = bsModalService;
        this.reload$ = new Subject();
        this.reloading$ = new BehaviorSubject(false);
        this.isSoftwareTypeChanged = false;
        this.updateSoftware$ = new Subject();
        this.softwareUpdated$ = new Subject();
        this.baseVersionsUpdated$ = new Subject();
        this.software$ = merge(this.activatedRoute.params.pipe(map(params => params.id), switchMap(id => from(this.inventoryService.detail(id).then(result => result.data)))), this.reload$.pipe(tap(() => this.reloading$.next(true)), switchMap(() => this.activatedRoute.params), map(params => params.id), switchMap(id => from(this.inventoryService.detail(id).then(result => result.data))), tap(() => this.reloading$.next(false))), this.softwareUpdated$).pipe(shareReplay(1));
        this.baseVersions$ = merge(this.software$.pipe(distinctUntilKeyChanged('id')), this.baseVersionsUpdated$, this.reload$).pipe(switchMap(() => this.software$), switchMap(software => this.repositoryService.listBaseVersions(software)), shareReplay(1));
        this.isLegacy$ = this.software$.pipe(map(software => this.repositoryService.isLegacyEntry(software)), shareReplay(1));
        this.destroy$ = new Subject();
    }
    ngOnInit() {
        this.updateSoftware$
            .pipe(withLatestFrom(this.software$), switchMap(([softwarePartial, software]) => this.inventoryService.update(Object.assign({ id: software.id }, softwarePartial))), map(({ data }) => data), tap(software => this.softwareUpdated$.next(software)), tap(() => this.alertService.success(gettext('Saved.'))), takeUntil(this.destroy$))
            .subscribe();
        this.software$.subscribe(software => {
            this.softwareTypeObject = software;
        });
    }
    getBinaryName$(binaryUrl) {
        return this.repositoryService.getBinaryName$(binaryUrl);
    }
    addBaseVersion() {
        this.software$
            .pipe(take(1), switchMap(software => {
            const initialState = {
                model: {
                    selected: software,
                    description: software.description
                }
            };
            const config = {
                class: 'modal-sm',
                ignoreBackdropClick: true,
                initialState
            };
            const modalRef = this.bsModalService.show(AddSoftwareModalComponent, config);
            return modalRef.content.saved;
        }))
            .subscribe(() => this.baseVersionsUpdated$.next());
    }
    deleteBaseVersion(baseVersion) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const title = gettext('Delete software');
                const body = `
        ${this.translateService.instant(gettext('You are about to delete software {{ version }}.'), { version: baseVersion.c8y_Software.version })}
        ${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(baseVersion);
                this.alertService.success(gettext('Software deleted.'));
                this.baseVersionsUpdated$.next();
            }
            catch (ex) {
                // only if not cancel from modal
                if (ex) {
                    this.alertService.addServerFailure(ex);
                }
            }
        });
    }
    onSelectSoftwareType(software) {
        var _a;
        this.isSoftwareTypeChanged = !(((_a = this.softwareTypeObject) === null || _a === void 0 ? void 0 : _a.softwareType) === (software === null || software === void 0 ? void 0 : software.softwareType));
        this.softwareTypeObject = software;
    }
    ngOnDestroy() {
        this.destroy$.next(true);
        this.destroy$.unsubscribe();
    }
}
SoftwareDetailsComponent.decorators = [
    { type: Component, args: [{
                selector: 'c8y-software-details',
                template: "<c8y-title>\n  {{ (software$ | async)?.name }}\n</c8y-title>\n\n<c8y-breadcrumb>\n  <c8y-breadcrumb-item\n    path=\"#/software\"\n    label=\"{{ 'Software repository' | translate }}\"\n    icon=\"c8y-tools\"\n  >\n  </c8y-breadcrumb-item>\n</c8y-breadcrumb>\n\n<c8y-action-bar-item [placement]=\"'right'\">\n  <button\n    *ngIf=\"!(isLegacy$ | async)\"\n    class=\"btn btn-link\"\n    title=\"{{ 'Add software' | translate }}\"\n    (click)=\"addBaseVersion()\"\n  >\n    <i c8yIcon=\"plus-circle\"></i>\n    {{ 'Add software' | translate }}\n  </button>\n</c8y-action-bar-item>\n\n<c8y-action-bar-item [placement]=\"'right'\">\n  <button class=\"btn btn-link\" title=\"{{ 'Reload' | translate }}\" (click)=\"reload$.next()\">\n    <i c8yIcon=\"refresh\" [ngClass]=\"{ 'icon-spin': reloading$ | async }\"></i>\n    {{ 'Reload' | translate }}\n  </button>\n</c8y-action-bar-item>\n\n<div class=\"row\">\n  <div class=\"col-lg-12 col-lg-max\">\n    <div class=\"card m-b-4\">\n      <div class=\"card-header separator\">\n        <h4 class=\"card-title\" translate>Software info</h4>\n      </div>\n      <div class=\"card-block overflow-visible\">\n        <div class=\"row\">\n          <div class=\"col-sm-6\">\n            <c8y-form-group>\n              <label class=\"control-label\">\n                {{ 'Name' | translate }}\n              </label>\n              <div class=\"input-group input-group-editable\">\n                <input\n                  #nameInput\n                  type=\"text\"\n                  class=\"form-control\"\n                  [ngModel]=\"(software$ | async)?.name\"\n                  #nameModel=\"ngModel\"\n                  placeholder=\"{{ 'e.g. My software' | translate }}\"\n                  [ngStyle]=\"{ 'width.ch': (software$ | async)?.name?.length + 2 || 31 }\"\n                  required\n                />\n                <span></span>\n                <div class=\"input-group-btn\">\n                  <button\n                    class=\"btn btn-primary\"\n                    title=\"{{ 'Save' | translate }}\"\n                    (click)=\"updateSoftware$.next({ name: nameInput.value }); nameModel.reset()\"\n                    [disabled]=\"nameInput.value.length === 0\"\n                  >\n                    {{ 'Save' | translate }}\n                  </button>\n                </div>\n              </div>\n            </c8y-form-group>\n          </div>\n          <div class=\"col-sm-6\">\n            <c8y-form-group>\n              <label class=\"control-label\">\n                {{ 'Description' | translate }}\n              </label>\n              <div class=\"input-group input-group-editable\">\n                <input\n                  #descriptionInput\n                  type=\"text\"\n                  class=\"form-control\"\n                  [ngModel]=\"(software$ | async)?.description\"\n                  #descriptionModel=\"ngModel\"\n                  placeholder=\"{{ 'e.g. Cloud connectivity software' | translate }}\"\n                  [ngStyle]=\"{ 'width.ch': (software$ | async)?.description?.length + 2 || 31 }\"\n                />\n                <span></span>\n                <div class=\"input-group-btn\">\n                  <button\n                    class=\"btn btn-primary\"\n                    title=\"{{ 'Save' | translate }}\"\n                    (click)=\"\n                      updateSoftware$.next({ description: descriptionInput.value });\n                      descriptionModel.reset()\n                    \"\n                  >\n                    {{ 'Save' | translate }}\n                  </button>\n                </div>\n              </div>\n            </c8y-form-group>\n          </div>\n        </div>\n        <div class=\"row\">\n          <div class=\"col-sm-6\">\n            <c8y-form-group>\n              <label class=\"control-label\">\n                {{ 'Device type' | translate }}\n                <button\n                  class=\"btn-clean\"\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                  [outsideClick]=\"true\"\n                  container=\"body\"\n                >\n                  <i c8yIcon=\"question-circle-o\" class=\"text-info\"></i>\n                </button>\n              </label>\n              <div class=\"input-group input-group-editable\">\n                <input\n                  #deviceTypeInput\n                  type=\"text\"\n                  class=\"form-control\"\n                  [ngModel]=\"(software$ | async)?.c8y_Filter?.type\"\n                  #deviceTypeModel=\"ngModel\"\n                  placeholder=\"{{ 'e.g.' | translate }} c8y_Linux\"\n                  [ngStyle]=\"{ 'width.ch': (software$ | async)?.type?.length + 2 || 31 }\"\n                />\n                <span></span>\n                <div class=\"input-group-btn\">\n                  <button\n                    class=\"btn btn-primary\"\n                    title=\"{{ 'Save' | translate }}\"\n                    (click)=\"\n                      updateSoftware$.next({ c8y_Filter: { type: deviceTypeInput.value } });\n                      deviceTypeModel.reset()\n                    \"\n                  >\n                    {{ 'Save' | translate }}\n                  </button>\n                </div>\n              </div>\n            </c8y-form-group>\n          </div>\n          <div class=\"col-sm-6\">\n            <c8y-form-group>\n              <label class=\"control-label\">\n                {{ 'Software type' | translate }}\n              </label>\n              <div class=\"input-group input-group-editable\">\n                <c8y-software-type\n                  [softwareTypeMO]=\"softwareTypeObject\"\n                  [style]=\"{ 'width.ch': softwareTypeObject?.softwareType?.length + 2 || 31 }\"\n                  (onSelectSoftware)=\"onSelectSoftwareType($event)\"\n                >\n                </c8y-software-type>\n                <div class=\"input-group-btn\">\n                  <button\n                    class=\"btn btn-primary\"\n                    [ngClass]=\"isSoftwareTypeChanged ? '' : 'hidden'\"\n                    title=\"{{ 'Save' | translate }}\"\n                    [disabled]=\"softwareTypeObject?.softwareType === ''\"\n                    (click)=\"\n                      updateSoftware$.next({ softwareType: softwareTypeObject.softwareType });\n                      softwareType.resetInput();\n                      isSoftwareTypeChanged = false\n                    \"\n                  >\n                    {{ 'Save' | translate }}\n                  </button>\n                </div>\n              </div>\n            </c8y-form-group>\n          </div>\n        </div>\n      </div>\n    </div>\n  </div>\n</div>\n\n<div class=\"row\">\n  <div class=\"col-lg-12 col-lg-max\">\n    <div class=\"card\">\n      <div class=\"card-header separator\">\n        <h4 class=\"card-title\" translate>Versions</h4>\n      </div>\n\n      <div class=\"card-block p-t-0 p-b-24\">\n        <div *ngIf=\"(baseVersions$ | async)?.data.length === 0\">\n          <div class=\"c8y-empty-state text-center\">\n            <h1 c8yIcon=\"c8y-tools\" class=\"c8y-icon-duocolor\"></h1>\n            <h3 translate>No versions to display.</h3>\n            <p translate>Add a new version by clicking below.</p>\n            <p>\n              <button\n                class=\"btn btn-primary\"\n                title=\"{{ 'Add software' | translate }}\"\n                (click)=\"addBaseVersion()\"\n              >\n                {{ 'Add software' | translate }}\n              </button>\n            </p>\n          </div>\n        </div>\n\n        <c8y-list-group\n          [ngClass]=\"{ 'dd-low': (baseVersions$ | async)?.data.length < 10 }\"\n          *ngIf=\"(baseVersions$ | async)?.data.length > 0\"\n        >\n          <c8y-li\n            *c8yFor=\"let baseVersion of baseVersions$ | async; let i = index; loadMore: 'auto'\"\n          >\n            <c8y-li-icon>\n              <i c8yIcon=\"c8y-tools\"></i>\n            </c8y-li-icon>\n\n            <c8y-li-body class=\"content-flex-50\">\n              <div class=\"col-4\">\n                <p class=\"text-truncate-wrap\" title=\"{{ baseVersion.c8y_Software.version }}\">\n                  {{ baseVersion.c8y_Software.version }}\n                </p>\n              </div>\n              <div class=\"col-5\">\n                <p class=\"text-truncate-wrap\">\n                  <span class=\"text-label-small m-r-8\" translate> File </span>\n                  <span title=\" {{ getBinaryName$(baseVersion.c8y_Software.url) | async }}\">\n                    <c8y-file-download url=\"{{ baseVersion.c8y_Software.url }}\"></c8y-file-download>\n                  </span>\n                </p>\n              </div>\n              <div class=\"col-2 flex-row a-i-start\">\n                <span *ngIf=\"isLegacy$ | async\" class=\"label label-warning flex-item-right-sm\">\n                  {{ 'Legacy' | translate }}\n                </span>\n\n                <div class=\"fit-h-20\" *ngIf=\"!(isLegacy$ | async)\">\n                  <button\n                    class=\"btn btn-danger btn-xs visible-xs flex-item-right m-r-8 m-t-8\"\n                    (click)=\"deleteBaseVersion(baseVersion)\"\n                    title=\"{{ 'Delete' | translate }}\"\n                  >\n                    <i c8yIcon=\"minus-circle\"></i>\n                    {{ 'Delete' | translate }}\n                  </button>\n                </div>\n              </div>\n              <div *ngIf=\"!(isLegacy$ | async)\" class=\"flex-item-right fit-h-20 p-r-8 hidden-xs\">\n                <button\n                  class=\"btn btn-dot text-danger showOnHover\"\n                  (click)=\"deleteBaseVersion(baseVersion)\"\n                  title=\"{{ 'Delete' | translate }}\"\n                >\n                  <i c8yIcon=\"minus-circle\"></i>\n                </button>\n              </div>\n            </c8y-li-body>\n          </c8y-li>\n        </c8y-list-group>\n      </div>\n    </div>\n  </div>\n</div>\n"
            },] }
];
SoftwareDetailsComponent.ctorParameters = () => [
    { type: ActivatedRoute },
    { type: InventoryService },
    { type: RepositoryService },
    { type: AlertService },
    { type: TranslateService },
    { type: ModalService },
    { type: BsModalService }
];
SoftwareDetailsComponent.propDecorators = {
    softwareType: [{ type: ViewChild, args: [SoftwareTypeComponent, { static: true },] }]
};
__decorate([
    memoize()
], SoftwareDetailsComponent.prototype, "getBinaryName$", null);
//# sourceMappingURL=data:application/json;base64, 