import * as i0 from '@angular/core';
import { Injectable, EventEmitter, Component, Input, Output, ViewChild, NgModule } from '@angular/core';
import * as i1 from '@c8y/client';
import { from, Subject, fromEvent, interval, NEVER, of } from 'rxjs';
import { map, merge, debounce, scan, tap, switchMap, takeUntil, filter, finalize, catchError, delay, repeat } from 'rxjs/operators';
import * as i2 from '@angular/common';
import * as i3 from '@c8y/ngx-components';
import { CommonModule } from '@c8y/ngx-components';
import { ButtonsModule } from 'ngx-bootstrap/buttons';

class AppLogsService {
    constructor(application) {
        this.application = application;
    }
    getLogs$(appId, instanceName, params = {}) {
        const formattedDateFrom = params.dateFrom ? this.formatDate(params.dateFrom) : null;
        const formattedDateTo = params.dateTo ? this.formatDate(params.dateTo) : null;
        const modifiedParams = {
            ...params,
            ...(formattedDateFrom && { dateFrom: formattedDateFrom }),
            ...(formattedDateTo && { dateTo: formattedDateTo })
        };
        return from(this.application.getInstanceLog(appId, instanceName, modifiedParams)).pipe(map(res => res.data));
    }
    formatDate(dateToFormat) {
        return new Date(dateToFormat).toISOString();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsService, deps: [{ token: i1.ApplicationService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i1.ApplicationService }] });

class AppLogsAutoRefreshComponent {
    set buttonsDisabled(areDisabled) {
        this.isAutoRefreshDisabled = areDisabled;
        if (areDisabled && this.isAutoRefreshOn) {
            this.isAutoRefreshOn = false;
            this.cancel$.next(false);
        }
    }
    constructor(appLogsService) {
        this.appLogsService = appLogsService;
        this.cancel$ = new Subject();
        this.isAutoRefreshDisabled = false;
        this.logsToOutput = this.getEmptyLogsJson();
        this.isAutoRefreshOn = true;
        this.onNewLogs = new EventEmitter();
        this.isRealtimeEnabled = new EventEmitter();
        this.toggleState = currentState => !currentState;
    }
    ngAfterViewInit() {
        const clicks$ = fromEvent(this.button.nativeElement, 'click').pipe(merge(this.cancel$), debounce(() => interval(300)), scan(this.toggleState, false), tap(isAutoRefreshOn => this.setButtonState(isAutoRefreshOn)), switchMap(isOn => (isOn ? this.watchForNewLogs() : NEVER)));
        this.subscription = clicks$.subscribe();
    }
    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
    setButtonState(isAutoRefreshOn) {
        this.isAutoRefreshOn = isAutoRefreshOn;
        this.isRealtimeEnabled.emit(isAutoRefreshOn);
    }
    watchForNewLogs() {
        return this.startPolling().pipe(takeUntil(this.cancel$.pipe(filter(isAutoRefreshOn => isAutoRefreshOn === false))), finalize(() => {
            this.isAutoRefreshOn = false;
        }));
    }
    startPolling() {
        return of(1).pipe(switchMap(() => this.getNewLogs().pipe(catchError(() => of(this.getEmptyLogsJson())))), tap(logs => this.updateLogsToOutput(logs)), delay(10000), repeat());
    }
    getNewLogs() {
        return this.appLogsService.getLogs$(this.getAppId(), this.getInstanceName());
    }
    getAppId() {
        return this.mo.applicationId;
    }
    getInstanceName() {
        return this.selectedInstance.name;
    }
    updateLogsToOutput(newLogs) {
        const { dateFrom, dateTo } = newLogs;
        if (dateFrom && dateTo) {
            this.logsToOutput = { ...newLogs };
            this.onNewLogs.emit(this.logsToOutput);
        }
    }
    getEmptyLogsJson() {
        return {
            dateFrom: null,
            dateTo: null,
            logs: '',
            truncated: false
        };
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsAutoRefreshComponent, deps: [{ token: AppLogsService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: AppLogsAutoRefreshComponent, selector: "c8y-app-logs-auto-refresh", inputs: { selectedInstance: "selectedInstance", mo: "mo", buttonsDisabled: "buttonsDisabled" }, outputs: { onNewLogs: "onNewLogs", isRealtimeEnabled: "isRealtimeEnabled" }, viewQueries: [{ propertyName: "button", first: true, predicate: ["autoRefresh"], descendants: true, static: true }], ngImport: i0, template: "<button #autoRefresh\n  type=\"button\"\n  class=\"btn btn-link c8y-realtime\"\n  [ngStyle]=\"{'width': 'auto'}\"\n  title=\"{{'Toggle auto refresh' | translate}}\"\n  [disabled]=\"isAutoRefreshDisabled\"\n>\n  <span class=\"c8y-pulse\" [ngClass]=\"isAutoRefreshOn ? 'active' : 'inactive'\"></span>\n  {{'Auto refresh' | translate}}\n</button>", dependencies: [{ kind: "directive", type: i2.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i2.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "pipe", type: i3.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsAutoRefreshComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-app-logs-auto-refresh', template: "<button #autoRefresh\n  type=\"button\"\n  class=\"btn btn-link c8y-realtime\"\n  [ngStyle]=\"{'width': 'auto'}\"\n  title=\"{{'Toggle auto refresh' | translate}}\"\n  [disabled]=\"isAutoRefreshDisabled\"\n>\n  <span class=\"c8y-pulse\" [ngClass]=\"isAutoRefreshOn ? 'active' : 'inactive'\"></span>\n  {{'Auto refresh' | translate}}\n</button>" }]
        }], ctorParameters: () => [{ type: AppLogsService }], propDecorators: { selectedInstance: [{
                type: Input
            }], mo: [{
                type: Input
            }], buttonsDisabled: [{
                type: Input
            }], onNewLogs: [{
                type: Output
            }], isRealtimeEnabled: [{
                type: Output
            }], button: [{
                type: ViewChild,
                args: ['autoRefresh', { static: true }]
            }] } });

class AppLogsAutoRefreshModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsAutoRefreshModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.13", ngImport: i0, type: AppLogsAutoRefreshModule, declarations: [AppLogsAutoRefreshComponent], imports: [CommonModule, ButtonsModule], exports: [AppLogsAutoRefreshComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsAutoRefreshModule, providers: [AppLogsService], imports: [CommonModule, ButtonsModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: AppLogsAutoRefreshModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [AppLogsAutoRefreshComponent],
                    exports: [AppLogsAutoRefreshComponent],
                    imports: [CommonModule, ButtonsModule],
                    providers: [AppLogsService]
                }]
        }] });

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

export { AppLogsAutoRefreshComponent, AppLogsAutoRefreshModule, AppLogsService };
//# sourceMappingURL=c8y-ngx-components-app-logs.mjs.map
