import { HttpClient } from 'aurelia-fetch-client';
import { noView } from 'aurelia-templating';
import { inject } from 'aurelia-dependency-injection';
import { EventAggregator } from 'aurelia-event-aggregator';
import * as nprogress from 'nprogress';

@noView(['nprogress/nprogress.css'])
@inject(EventAggregator, HttpClient)
export class LoadingIndicator {
    constructor(eventAggregator: EventAggregator, httpClient: HttpClient ) {
        nprogress.configure({ showSpinner: false });
        // eventAggregator.subscribe('router:navigation:processing', this.start);
        // eventAggregator.subscribe('router:navigation:complete', this.done);
         eventAggregator.subscribe('flow:uploading', (e) => this.start(e, false));
         eventAggregator.subscribe('flow:progress', this.progress);
         eventAggregator.subscribe('flow:complete', this.done);

        let requestFn = (message) => {
            this.start(null);
            console.log(message);
            return message; 
        
        }
        let responseFn = (response: Response) => {
            this.done();
            return response;
        }
        httpClient.configure(config =>
           { 
                config.withInterceptor({
                    request: requestFn,
                    response: responseFn
                });

            });
    }

    start(e, random = true) {            
        nprogress.start();
        if (random)
            nprogress.inc();
    }
    progress(progression: number) {
        nprogress.set(progression);
    }
    done() {
        nprogress.done();
    }
}