import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Component, Injectable, Injector} from "@angular/core";
import {MatSnackBar} from "@angular/material/snack-bar";
import {Observable} from "rxjs";
import {tap} from 'rxjs/operators';

@Component({
  template: `
    <section><p>Ожидание ответа от сервера</p>
      <mat-progress-bar value="40" color="warn" mode="indeterminate"></mat-progress-bar>
    </section>`,
  styles: [`
    p {
      font-family: Arial, Helvetica, sans-serif;
      text-align: center
    }
  `]
})
export class PendingSnackBar {
}

@Injectable()
export class PendingIndicator implements HttpInterceptor {

  private snackBarRef;

  constructor(private injector: Injector) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log("Pending indicator");

    var t = setTimeout(_ => {
      this.show()
    }, 500);

    return next.handle(req).pipe(tap(() => {
      clearTimeout(t);
      console.log("Pending indicator finally");
      this.close();
    }))
  }

  private getSnackBar() {
    return this.injector.get(MatSnackBar);
  };

  private show() {
    this.snackBarRef = this.getSnackBar().openFromComponent(PendingSnackBar);
  }

  private close() {
    if (this.snackBarRef !== undefined)
      this.snackBarRef.dismiss();
  }


}
