import {AlertController, App, Events} from 'ionic-angular';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Storage} from '@ionic/storage';

import {Observable} from 'rxjs';
import {_throw} from 'rxjs/observable/throw';
import {CommonService} from "./common.service";

/**
 * http拦截器  增加token信息
 */

@Injectable()
export class InterceptorProvider implements HttpInterceptor {

    constructor(private storage: Storage, private alertCtrl: AlertController, private events: Events,
                private commonSer: CommonService, private app: App) {
    }

    // Intercepts all HTTP requests!
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let promise = this.storage.get('Authorization');
        return Observable.fromPromise(promise)
            .mergeMap(token => {
                let clonedReq = this.addToken(request, token);
                return next.handle(clonedReq).do(res => {
                    if (res instanceof HttpResponse) {
                    }
                }, (error) => {
                    let msg = error.message;
                    this.message(error);
                    // Pass the error to the caller of the function
                    return _throw(error);
                }, () => {
                })
            });
    }

    // Adds the token to your headers if it exists
    private addToken(request: HttpRequest<any>, Authorization: any) {
        if (Authorization) {
            let clone: HttpRequest<any>;
            clone = request.clone({
                setHeaders: {
                    // "Accept": `application/json`,
                    'Content-Type': `application/json`,
                    "Authorization": `Bearer ${Authorization}`
                }
            });
            return clone;
        }
        return request;
    }

    message(data) {
        if (data.status) {
            let code = data.status;
            if (code == 401) {
                this.commonSer.toast("登录已过期");
                this.storage.clear();
                this.events.publish('toLogin');
            } else {
                // const error = JSON.parse(data.error);
                // let alert = this.alertCtrl.create({
                //     title: "错误",
                //     message: `${data.error.errorMsg}。`,
                //     buttons: ['确定']
                //     //title: error.name,
                //     //message: msg,
                //     //buttons: ['确定']
                // });
                // alert.present();
            }

        }
    }
}
