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: `
    <div *ngIf="report" class="cache-progress">
        <div class="uk-position-relative" [attr.uk-tooltip]="'Caching indicators process for ' + alias">
            <div class="uk-progress-circle" [attr.percentage]="report.percentage?report.percentage:0" [style]="'--percentage: ' + (report.percentage?report.percentage:0)"></div>
            <button *ngIf="report.percentage === 100" (click)="clear()" class="uk-icon-button uk-icon-button-xsmall uk-button-default uk-position-top-right"><icon name="close" [flex]="true" ratio="0.8"></icon></button>
        </div>
    </div>
  `,
  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();
  }
}
