import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/service/auth.service';
import { CookieService } from 'src/app/service/cookie.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(
    private authenticationService:AuthService,
    private router:Router,
    private cookieService:CookieService,
    private message:NzMessageService
  ) {}

  intercept(
    request:HttpRequest<any>,
    next:HttpHandler,
  ):Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((err) => {
        let printError = false;

        if (err.status == 401) {
          let message = 'Invalid Authentication Credentials';
          if (err && err.error && err.error.msg) {
            message = err.error.msg;
          }
          this.message.error(message, {
            nzDuration: 3000
          });
          if (!err.url.includes('logout_handler')) {
            this.authenticationService.logout();
          }
        } else if (err.status == 403) {
          let message = 'You are either not having right permission for accessing this module or your organization\'s license has expired. Please re-login or contact your administrator';
          if (err && err.error && err.error.msg) {
            message = err.error.msg;
          }

          const loginMethod = this.cookieService.get('login_method');
          if (loginMethod === 'mobile') {
            message = 'Failed to logging due to verficiation code not matched.';
          }

          this.message.error(message, {
            nzDuration: 3000
          });
        } else if (err.status == 409) {
          this.message.error('Your account was login in another location or login timeout', {
            nzDuration: 3000
          });
          this.authenticationService.logout();
        } else if (err.status == 400) {
          let reasonText = (err.error && err.error.reason) || 'Got Invalid Inputs Error';
          reasonText += ' (Please Make Sure Inputs Are Valid)';
          this.message.error(reasonText, {
            nzDuration: 3000
          });
        } else if (err.status == 413) {
          let reasonText = (err.error && err.error.reason) || 'The attachment file is too large';
          reasonText += ' (Confirm that the attachment is less than 2M)';
          this.message.error(reasonText, {
            nzDuration: 3000
          });
        } else if (err.status == 500) {
          printError = true;

          let reasonText = 'Got Unexpected Error';
          reasonText += ' (Please Contact Your Administrator)';
          this.message.error(reasonText, {
            nzDuration: 3000
          });
        } else {
          printError = true;

          let reasonText = 'Got Unexpected Error';
          reasonText += ' (Please Contact Your Administrator)';
          this.message.error(reasonText, {
            nzDuration: 3000
          });
        }

        let error;
        if (err.error) {
          if (printError) {
            console.error(`Error Status Code: ${err.status}`);
            if (err.error.reason) {
              console.error(`Error Reason: ${err.error.reason}`);
            }
            if (err.error.traceback) {
              console.error(`Error Backend Traceback: ${err.error.traceback}`);
            }
          }

          error = err.error.reason;
        } else {
          error = err.statusText;
        }

        return throwError(error);
      }),
    );
  }
}
