import { NgIf } from '@angular/common';
import * as i0 from '@angular/core';
import { EventEmitter, inject, ViewChild, Output, Input, Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { OperationStatus, OperationService } from '@c8y/client';
import { gettext } from '@c8y/ngx-components/gettext';
import { AlertService, IconDirective, DataGridComponent, EmptyStateComponent, C8yTranslatePipe } from '@c8y/ngx-components';
import * as i1 from '@c8y/ngx-components/operations/bulk-operations-service';
import { OperationStatusGridColumn, DeviceGridColumn, CreationTimeGridColumn, FailureReasonGridColumn } from '@c8y/ngx-components/operations/grid-columns';
import { OPERATION_STATUS_LABELS, OPERATION_STATUS_OPTIONS_MAP } from '@c8y/ngx-components/operations/shared';
import * as i2 from '@c8y/ngx-components/operations/status-filter';
import { StatusFilterModule, StatusFilterComponent } from '@c8y/ngx-components/operations/status-filter';
import { omit } from 'lodash-es';
import { Subject, merge, throttleTime } from 'rxjs';

class SingleOperationsListComponent {
    constructor(bulkOperationsService) {
        this.bulkOperationsService = bulkOperationsService;
        this.readOnly = false;
        this.onRetryFailedOperations = new EventEmitter();
        this.OPERATION_STATUS = { ...OperationStatus, ALL: gettext('ALL') };
        this.OPERATION_STATUS_LABELS = OPERATION_STATUS_LABELS;
        this.OPERATION_STATUS_OPTIONS_MAP = OPERATION_STATUS_OPTIONS_MAP;
        this.displayOptions = {
            gridHeader: false
        };
        this.pagination = {
            pageSize: 25,
            currentPage: 1
        };
        this.columns = [
            new OperationStatusGridColumn(),
            new DeviceGridColumn(),
            new CreationTimeGridColumn(),
            new FailureReasonGridColumn()
        ];
        this.actions = [
            {
                type: 'retry',
                icon: 'repeat',
                label: gettext('Retry operation'),
                text: gettext('Retry operation'),
                callback: operation => {
                    this.retrySingleOperation(operation);
                },
                showIf: operation => !this.readOnly &&
                    operation.status.toString() === OPERATION_STATUS_OPTIONS_MAP.FAILED.status.toString()
            }
        ];
        this.operationService = inject(OperationService);
        this.alertService = inject(AlertService);
        this.reload$ = new Subject();
        this.reloadThrottled$ = new Subject();
        this.serverSideDataCallback = this.onDataSourceModifier.bind(this);
        merge(this.reload$, this.reloadThrottled$.pipe(throttleTime(30_000)))
            .pipe(takeUntilDestroyed())
            .subscribe(() => this.dataGrid?.reload(false));
    }
    async ngAfterViewInit() {
        if (this.statusFilter) {
            this.setStatusFilter(false);
        }
    }
    ngOnChanges(changes) {
        if (changes.bulkOperation && !changes.bulkOperation.firstChange) {
            this.reloadThrottled$.next();
        }
    }
    reload(option) {
        const [opt] = option ?? [];
        this.filterStatus = opt?.status ?? this.filterStatus;
        this.reload$.next();
    }
    async onDataSourceModifier(dataSourceModifier) {
        const filter = this.filterStatus ?? this.getFilterTypeOfSingleOperations();
        const { res, data, paging } = await this.bulkOperationsService.getSingleOperationsByStatus(filter, this.bulkOperation.id, dataSourceModifier.pagination);
        const filteredSize = await this.bulkOperationsService.getSingleOperationsCountByStatus(filter, this.bulkOperation.id);
        const size = await this.bulkOperationsService.getSingleOperationsTotal(this.bulkOperation.id);
        const serverSideDataResult = { res, data, paging, filteredSize, size };
        return serverSideDataResult;
    }
    setStatusFilter(emit = true) {
        if (this.statusFilter) {
            const typeFilter = this.getFilterTypeOfSingleOperations();
            this.statusFilter.preset(typeFilter === this.OPERATION_STATUS.ALL
                ? []
                : [{ label: this.OPERATION_STATUS_LABELS[typeFilter] }], emit);
        }
        else {
            setTimeout(this.setStatusFilter.bind(this, emit));
        }
    }
    getFilterTypeOfSingleOperations() {
        const { progress } = this.bulkOperation;
        if (progress.failed > 0) {
            return this.OPERATION_STATUS.FAILED;
        }
        else if (progress.failed === 0 && progress.successful === 0 && progress.pending === 0) {
            return this.OPERATION_STATUS.EXECUTING;
        }
        else if (progress.failed === 0 && progress.successful === 0 && progress.executing === 0) {
            return this.OPERATION_STATUS.PENDING;
        }
        else if (progress.failed === 0 && progress.pending === 0 && progress.executing === 0) {
            return this.OPERATION_STATUS.SUCCESSFUL;
        }
        return this.OPERATION_STATUS.ALL;
    }
    retryBulkOperation() {
        this.onRetryFailedOperations.emit(this.bulkOperation);
    }
    async retrySingleOperation(singleOperation) {
        const operationToCreate = omit(singleOperation, [
            'id',
            'self',
            'status',
            'failureReason',
            'creationTime',
            'delivery'
        ]);
        try {
            await this.operationService.create(operationToCreate);
            this.alertService.success(gettext('Operation created.'));
        }
        catch (er) {
            this.alertService.addServerFailure(er);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.16", ngImport: i0, type: SingleOperationsListComponent, deps: [{ token: i1.BulkOperationsService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.16", type: SingleOperationsListComponent, isStandalone: true, selector: "c8y-single-operations-list", inputs: { bulkOperation: "bulkOperation", readOnly: "readOnly" }, outputs: { onRetryFailedOperations: "onRetryFailedOperations" }, viewQueries: [{ propertyName: "statusFilter", first: true, predicate: StatusFilterComponent, descendants: true }, { propertyName: "dataGrid", first: true, predicate: DataGridComponent, descendants: true }], usesOnChanges: true, ngImport: i0, template: "<ng-container\n  *ngIf=\"\n    bulkOperation.progress.failed ||\n    bulkOperation.progress.executing ||\n    bulkOperation.progress.pending ||\n    bulkOperation.progress.successful\n  \"\n>\n  <div\n    class=\"legend form-block p-t-16 m-b-0\"\n    translate\n  >\n    Operations\n  </div>\n  <div class=\"d-flex a-i-center\">\n    <div class=\"d-flex a-i-center p-b-8\">\n      <span\n        class=\"m-r-4 text-medium\"\n        translate\n      >\n        Filter by status\n      </span>\n      <c8y-status-filter\n        small\n        [options]=\"OPERATION_STATUS_OPTIONS_MAP\"\n        (onFilterChanged)=\"reload($event)\"\n      ></c8y-status-filter>\n    </div>\n    <div\n      class=\"m-l-auto p-b-8\"\n      *ngIf=\"!readOnly && bulkOperation.progress.failed > 0\"\n    >\n      <button\n        class=\"btn btn-navbar\"\n        title=\"{{ 'Retry failed operations' | translate }}\"\n        (click)=\"retryBulkOperation()\"\n      >\n        <i\n          class=\"m-r-4\"\n          c8yIcon=\"repeat\"\n        ></i>\n        <span translate>Retry failed operations</span>\n      </button>\n    </div>\n  </div>\n  <c8y-data-grid\n    [actionControls]=\"actions\"\n    [columns]=\"columns\"\n    [displayOptions]=\"displayOptions\"\n    [serverSideDataCallback]=\"serverSideDataCallback\"\n    [pagination]=\"pagination\"\n  >\n    <c8y-ui-empty-state\n      icon=\"search\"\n      [title]=\"'No single operations of the selected status to display.' | translate\"\n      [subtitle]=\"'Single operations will be displayed here' | translate\"\n      horizontal\n    ></c8y-ui-empty-state>\n  </c8y-data-grid>\n</ng-container>\n", dependencies: [{ kind: "ngmodule", type: StatusFilterModule }, { kind: "component", type: i2.StatusFilterComponent, selector: "c8y-status-filter", inputs: ["options", "multiple", "small"], outputs: ["onFilterChanged"] }, { kind: "directive", type: NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "component", type: DataGridComponent, selector: "c8y-data-grid", inputs: ["title", "loadMoreItemsLabel", "loadingItemsLabel", "showSearch", "refresh", "columns", "rows", "pagination", "childNodePagination", "infiniteScroll", "serverSideDataCallback", "selectable", "singleSelection", "selectionPrimaryKey", "displayOptions", "actionControls", "bulkActionControls", "headerActionControls", "searchText", "configureColumnsEnabled", "showCounterWarning", "activeClassName", "expandableRows", "treeGrid", "hideReload", "childNodesProperty", "parentNodeLabelProperty"], outputs: ["rowMouseOver", "rowMouseLeave", "rowClick", "onConfigChange", "onBeforeFilter", "onBeforeSearch", "onFilter", "itemsSelect", "onReload", "onAddCustomColumn", "onRemoveCustomColumn", "onColumnFilterReset", "onSort", "onPageSizeChange", "onColumnReordered", "onColumnVisibilityChange"] }, { kind: "component", type: EmptyStateComponent, selector: "c8y-ui-empty-state", inputs: ["icon", "title", "subtitle", "horizontal"] }, { kind: "pipe", type: C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.16", ngImport: i0, type: SingleOperationsListComponent, decorators: [{
            type: Component,
            args: [{ standalone: true, selector: 'c8y-single-operations-list', imports: [
                        StatusFilterModule,
                        NgIf,
                        C8yTranslatePipe,
                        IconDirective,
                        DataGridComponent,
                        EmptyStateComponent
                    ], template: "<ng-container\n  *ngIf=\"\n    bulkOperation.progress.failed ||\n    bulkOperation.progress.executing ||\n    bulkOperation.progress.pending ||\n    bulkOperation.progress.successful\n  \"\n>\n  <div\n    class=\"legend form-block p-t-16 m-b-0\"\n    translate\n  >\n    Operations\n  </div>\n  <div class=\"d-flex a-i-center\">\n    <div class=\"d-flex a-i-center p-b-8\">\n      <span\n        class=\"m-r-4 text-medium\"\n        translate\n      >\n        Filter by status\n      </span>\n      <c8y-status-filter\n        small\n        [options]=\"OPERATION_STATUS_OPTIONS_MAP\"\n        (onFilterChanged)=\"reload($event)\"\n      ></c8y-status-filter>\n    </div>\n    <div\n      class=\"m-l-auto p-b-8\"\n      *ngIf=\"!readOnly && bulkOperation.progress.failed > 0\"\n    >\n      <button\n        class=\"btn btn-navbar\"\n        title=\"{{ 'Retry failed operations' | translate }}\"\n        (click)=\"retryBulkOperation()\"\n      >\n        <i\n          class=\"m-r-4\"\n          c8yIcon=\"repeat\"\n        ></i>\n        <span translate>Retry failed operations</span>\n      </button>\n    </div>\n  </div>\n  <c8y-data-grid\n    [actionControls]=\"actions\"\n    [columns]=\"columns\"\n    [displayOptions]=\"displayOptions\"\n    [serverSideDataCallback]=\"serverSideDataCallback\"\n    [pagination]=\"pagination\"\n  >\n    <c8y-ui-empty-state\n      icon=\"search\"\n      [title]=\"'No single operations of the selected status to display.' | translate\"\n      [subtitle]=\"'Single operations will be displayed here' | translate\"\n      horizontal\n    ></c8y-ui-empty-state>\n  </c8y-data-grid>\n</ng-container>\n" }]
        }], ctorParameters: () => [{ type: i1.BulkOperationsService }], propDecorators: { bulkOperation: [{
                type: Input
            }], readOnly: [{
                type: Input
            }], onRetryFailedOperations: [{
                type: Output
            }], statusFilter: [{
                type: ViewChild,
                args: [StatusFilterComponent, { static: false }]
            }], dataGrid: [{
                type: ViewChild,
                args: [DataGridComponent, { static: false }]
            }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { SingleOperationsListComponent };
//# sourceMappingURL=c8y-ngx-components-operations-bulk-single-operations-list.mjs.map
