import { Injector } from '@angular/core';
import {
    HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse,
    HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { LoginService } from '../../shared/login/login.service';
import {NzMessageService} from 'ng-zorro-antd';

export class AuthExpiredInterceptor implements HttpInterceptor {

    constructor(
        private injector: Injector,
        private message: NzMessageService,
    ) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).do((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                if( event.body.errCode == 10100 ){
                   const loginService: LoginService = this.injector.get(LoginService);
                   loginService.logout();
               }
            }
        }, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                if (err.status === 401) {
                    const loginService: LoginService = this.injector.get(LoginService);
                    loginService.logout();
                }
            }
        });
    }
}
