import { ChangeDetectorRef, Component, Input, OnInit } from '@angular/core';
import { NbDialogRef } from '@nebular/theme';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { ProgressBarDlgConfig } from '../../../services/progress-bar-dlg.service';
import { RbjDialogService } from '../../../services/rbj-dialog.service';
import { SignalRService } from '../../../services/signal-r.service';

@Component({
  selector: 'ngx-progress-bar-dlg',
  templateUrl: './progress-bar-dlg.component.html',
  styleUrls: ['./progress-bar-dlg.component.scss']
})
export class ProgressBarDlgComponent implements OnInit {
  private destroy$: Subject<void> = new Subject<void>();
  private _percentIterateCount: number = 0;
  percent: number = 25;

  config: ProgressBarDlgConfig;

  rainbowStatus = [
    { status: 'danger', percent: 25 },
    { status: 'warning', percent: 50 },
    { status: 'info', percent: 75 },
    { status: 'success', percent: 100 },
  ]

  public get progressBarStatus(): string {
    return this.config.useRainbowStatus ? this.rainbowStatus.find(r => r.percent >= this.percent).status : this.config.status;
  }
  public get progressBarMessage(): string {
    let message = this.percent >= 100 ? 'Finished' : this.config.message;
    //if (this.config.showPercent) message += ` - ${this.percent}%`;
    return message;
  }

  constructor(
    private dlgService: RbjDialogService,
    private cdRef: ChangeDetectorRef,
    private dlgRef: NbDialogRef<ProgressBarDlgComponent>,
    private signalRService: SignalRService
  ) {

  }

  ngOnInit() {
    if (this.config.enableIterators) {
      setTimeout(() => {
        this.percentageIteration();
      }, 500);
    }

    if (this.config.signalRTag) {
      this.signalRService.ApiMessageSubject.pipe(takeUntil(this.destroy$),
        filter(r => r.tag == this.config.signalRTag))
        .subscribe(result => {

          let isProgressBarStatus = result.value['percentage'] > 0;

          if (isProgressBarStatus) {
            let progressStatus = result.value as ProgressBarStatus;
            if (progressStatus) {
              this.percent = Math.max(progressStatus.percentage, this.percent);
              this.config.message = progressStatus.message;
              this.cdRef.detectChanges();
              if (this.percent >= 100) setTimeout(() => { this.dlgRef.close(true); }, 300);
            }
          } else {

            let stage = this.config.signalRStages.find(s => s.signalRMsg == result.value);
            if (stage) {
              this.percent = Math.max(stage.percent, this.percent);
              this.config.message = stage.message;
              this.cdRef.detectChanges();
              if (this.percent >= 100) setTimeout(() => { this.dlgRef.close(true); }, 300);
            } else {
              this.config.message = result.value;
            }
          }
        });
    }


    this.dlgService.updateProgressBar$.pipe(takeUntil(this.destroy$))
      .subscribe(result => {
        this.percent = Math.max(result.percent, this.percent);
        this.config.message = result.message;
        this.cdRef.detectChanges();
        if (this.percent >= 100) setTimeout(() => { this.dlgRef.close(true); }, 300);
      });
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  percentageIteration() {
    setTimeout(() => {
      if (this.percent < 95) {
        this.percent += 1;
        this._percentIterateCount += 1;
        if (this._percentIterateCount > 10) {
          this._percentIterateCount = 0;
          let stage = this.config.signalRStages.find(s => s.percent > this.percent);
          if (stage && stage.message) this.config.message = stage.message;
        }
        this.percentageIteration();
      }
    }, this.percent < 60 ? 300 : this.percent < 80 ? 600 : 900);
  }





}

export interface ProgressBarStatus {
  message: string;
  percentage: number;
}