import {Component, Inject, Input, OnChanges, OnDestroy, OnInit, PLATFORM_ID, SimpleChanges} from "@angular/core";
import {Report} from "./cache-indicators";
import {CacheIndicatorsService} from "./cache-indicators.service";
import {interval, Subject, Subscription} from "rxjs";
import {map, switchMap, takeUntil} from "rxjs/operators";
@Component({
selector: 'cache-indicators',
template: `
`,
styleUrls: ['cache-indicators.component.less']
})
export class CacheIndicatorsComponent implements OnInit, OnChanges, OnDestroy {
report: Report;
subscriptions: Subscription[] = [];
interval: number = 10000;
readonly destroy$ = new Subject();
@Input() alias: string;
constructor(private cacheIndicatorsService: CacheIndicatorsService,
@Inject(PLATFORM_ID) private platformId) {
}
ngOnInit() {
this.getReport();
}
ngOnChanges(changes: SimpleChanges) {
if(changes.alias) {
this.getReport();
}
}
getReport() {
this.clear();
this.subscriptions.push(this.cacheIndicatorsService.getReport(this.alias).subscribe(report => {
this.getReportInterval(report);
}));
}
getReportInterval(report: Report) {
if(this.isBrowser && (this.report || !report?.completed)) {
this.report = report;
this.subscriptions.push(interval(this.interval).pipe(
map(() => this.cacheIndicatorsService.getReport(this.alias)),
switchMap(report => report),
takeUntil(this.destroy$)).subscribe(report => {
console.log(this.alias);
this.report = report;
if(this.report.completed) {
this.destroy$.next();
}
}));
}
}
clear() {
this.subscriptions.forEach(subscription => {
subscription.unsubscribe();
})
this.report = null;
}
get isBrowser() {
return this.platformId === 'browser';
}
ngOnDestroy() {
this.clear();
}
}