
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from "@angular/core"
import { Observable, of, throwError } from "rxjs";
import { tap, catchError, first } from "rxjs/operators";
import { Router } from '@angular/router';

import 'style-loader!angular2-toaster/toaster.css';
import {
  NbComponentStatus,
  NbGlobalPhysicalPosition,
  NbGlobalPosition,
  NbToastrService,
} from '@nebular/theme';
import { AuthService } from '../../services/auth.service';


@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  //#region toster config
  //index = 1;
  now: Date = new Date();
  destroyByClick = true;
  //1000 = 1sec
  duration = 2000;
  hasIcon = true;
  position: NbGlobalPosition = NbGlobalPhysicalPosition.TOP_RIGHT;
  preventDuplicates = false;
  status: NbComponentStatus = "danger";

  title = "Authentication Error";
  content = "";

  // positions: string[] = [
  //   NbGlobalPhysicalPosition.TOP_RIGHT,
  //   NbGlobalPhysicalPosition.TOP_LEFT,
  //   NbGlobalPhysicalPosition.BOTTOM_LEFT,
  //   NbGlobalPhysicalPosition.BOTTOM_RIGHT,
  //   NbGlobalLogicalPosition.TOP_END,
  //   NbGlobalLogicalPosition.TOP_START,
  //   NbGlobalLogicalPosition.BOTTOM_END,
  //   NbGlobalLogicalPosition.BOTTOM_START,
  // ];
  //#endregion

  constructor(
    private toastrService: NbToastrService,
    private router: Router,
    //private logger: LogService,
    //private httpErrorService: HttpErrorService,
    private authService: AuthService
  ) { }

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    //
    // this.logger.level = LogLevel[this.appConfig.getLogLevel()];
    // this.logger.debug('at HttpErrorInterceptor...');

    if (request.url.startsWith('/evo/')) return next.handle(request);

    return next.handle(request).pipe(

      tap((evt) => {
        if (evt instanceof HttpResponse) {
          const data = evt.body;


          // if(evt.body && evt.body.success){
          //   
          //   //this.toasterService.success(evt.body.success.message, evt.body.success.title, { positionClass: 'toast-bottom-center' });
          // }

          //RBJ Identity specific!!!
          //Display authentiction message from server if any of the followings is true
          // if (data.isAuthenticated != undefined) {
          //   if (
          //     !data.isAuthenticated ||
          //     !data.isAuthorized ||
          //     data.isChangePassword
          //   ) {
          //     this.content = data.message;
          //     this.showToast(this.status, this.title, this.content);
          //   }


          if (data && data.isAuthenticated != undefined) {
            if (
              !data.isAuthenticated ||
              !data.isAuthorized ||
              data.isChangePassword
            ) {
              this.status = "danger";
              this.title = "Authentication Error";
            } else {
              this.status = "success";
              this.title = "Authentication Info";
            }
            this.now = new Date();
            this.content = data.message + ' Occurred at ' +
              this.now.toLocaleString().replace(",", "");
            this.showToast(this.status, this.title, this.content);
            if (data.message === 'Token Expired.') {
              this.authService.logout();
              //this.router.navigate(['/auth/login']);
            }
          }
        }
      }),
      catchError((err: any) => {
        if (err instanceof HttpErrorResponse) {
          //this.logger.level = LogLevel[this.appConfig.getLogLevel()];
          //this.logger.fatal("at HttpErrorInterceptor.catchError.if (err instanceof HttpErrorResponse)...", err.url, err);
          const responseError = err;

          const error = err.error;

          this.status = "danger";

          if (error && error.isAuthenticated != undefined) {
            if (
              !error.isAuthenticated ||
              !error.isAuthorized ||
              error.isChangePassword
            ) {
              this.title = "Authentication Error";

              this.now = new Date();
              this.content = error.message + ' Occurred at ' +
                this.now.toLocaleString().replace(",", "");
              this.showToast(this.status, this.title, this.content);
              if (error.message === 'Token Expired.') {
                this.authService.logout();
                //this.router.navigate(['/auth/login']);
              }
            }
          } else {
            try {

              // this.logger.level = LogLevel[this.appConfig.getLogLevel()];
              // this.logger.fatal("at HttpErrorInterceptor.catchError.else...", responseError.url, responseError);

              // let errorTrackNo = -1;
              // if (responseError.error.exceptionMessage.indexOf('Error Track No:') == 0) {
              //   errorTrackNo = Number.parseInt(responseError.error.exceptionMessage.replace('Error Track No:', ''));
              // }

              // this.httpErrorService.showError(JSON.stringify(responseError), errorTrackNo).pipe(first()).subscribe(result => {
              //   if (result && result > -1) {
              //     this.router.navigate(['/rbj-utils/logs'], { queryParams: { trackNo: result }, queryParamsHandling: 'merge' });
              //   }
              // });



              // this.title = "Error";

              // this.now = new Date();
              // this.content = this.appConfig.getAuthServiceHttpErrorMessage() + ' @' +
              //   this.now.toLocaleString().replace(",", "");
              // this.showToast(this.status, this.title, this.content);


              //this.toasterService.error(err.error.message, err.error.title, { positionClass: 'toast-bottom-center' });
            } catch (e) {
              this.now = new Date();
              // this.content = this.appConfig.getDefaultUnexpectedErrorMessage() + ' Occurred at ' +
              //   this.now.toLocaleString().replace(",", "");
              // this.showToast(this.status, this.title, this.content);
              //this.toasterService.error('An error occurred', '', { positionClass: 'toast-bottom-center' });
            }
          }
          //log error
        }
        return throwError(err);
        //return of(err);
      })
    );
  }

  private showToast(type: NbComponentStatus, title: string, body: string) {
    const config = {
      status: type,
      destroyByClick: this.destroyByClick,
      duration: this.duration,
      hasIcon: this.hasIcon,
      position: this.position,
      preventDuplicates: this.preventDuplicates,
    };
    //const titleContent = title ? `. ${title}` : "";
    const titleContent = title ? title : "";

    //this.index += 1;
    this.now = new Date();

    this.toastrService.show(body, titleContent, config);
  }
}
