import {JhiEventManager} from 'ng-jhipster';
import {HttpInterceptor, HttpRequest, HttpErrorResponse, HttpHandler, HttpEvent} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import {NzMessageService, NzNotificationService} from 'ng-zorro-antd';

export class ErrorHandlerInterceptor implements HttpInterceptor {

    constructor(private eventManager: JhiEventManager, private message: NzMessageService,
                public notification: NzNotificationService) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).do((event: HttpEvent<any>) => {
        }, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                this.messageInfo(err);
            }
        });
    }

    messageInfo(err) {
        const status = err.status;
        switch (status) {
            case 401:
                this.notification.create('error', '错误', '登录信息已过期', {nzDuration: 2000});
                break;
            case 404:
                this.notification.create('error', '错误', `${err.url}不存在`, {nzDuration: 2000});
                break;
            case 500:
                this.notification.create('error', '错误', `${err.message}`, {nzDuration: 2000});
                break;
        }
    }
}
