import {Injectable, Injector} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, of, throwError} from 'rxjs';
import {catchError, retry} from 'rxjs/operators';


/**
 * HTTP拦截器,设置头部信息，及统一的错误处理
 */
@Injectable()
export class FrameHttpInterceptor implements HttpInterceptor {
  private headers: HttpHeaders;
  constructor(private inject: Injector) {
    this.headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8','Accept': 'application/json, text/javascript, */*; q=0.01','X-Requested-With':'XMLHttpRequest'});
  }

  /**
   * 拦截器拦截请求
   */
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const newReq = req.clone({ headers: this.headers});
    newReq.headers.set('frame_access_token', 'my-new-auth-token');
    return next.handle(newReq)
      .pipe(
        /*失败时重试2次，可自由设置*/
        retry(1),
        /*捕获响应错误，可根据需要自行改写，我偷懒了，直接用的官方的*/
        catchError(this.handleError)
      );

  }

  private handleError( error: HttpErrorResponse ) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}
