import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { StateManagementService } from '@services/state-management.service';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AutoLogoutInterceptorService implements HttpInterceptor {

  constructor(
    private navController: NavController,
    public alert: AlertService,
    private stateManagementService: StateManagementService,
  ) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((err) => {
        console.log(err);
        if (err && err.status === 401) {
          this.stateManagementService.token = '';
          this.stateManagementService.storage.remove(GJainStorage.loginType);
          this.stateManagementService.storage.remove(GJainStorage.profileData);
          this.stateManagementService.storage.remove(GJainStorage.userData).then(() => {
            this.navController.navigateRoot(Roots.auth + '/' + Roots.login);
          });
        }

        if (err.status === 0) {
          this.alert.showToasterError('Please check internet connectivity');
        }
        else if (err.status === 500) {
          this.alert.showToasterError('Internal server error');
        }
        else {
          if (!request.url.includes('?t=1')) {
            this.alert.showToasterError(err.error.message || err.message);
          }
        }
        console.log({ err });
        return throwError(err);
      })
    );
  }
}
