import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Hypermedia } from '../interfaces';
import { HeaderProvider } from './header-provider';
import { HrefFormatterProvider } from './href-formatter-provider.service';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class ResourceFetcher {
    constructor(
        private http: HttpClient,
        private headerProvider: HeaderProvider,
        private applicationScopeHrefFormatterProvider: HrefFormatterProvider) { }

    get(path: string,
        scope: string = 'local',
        authorize: boolean = true,
        tokenOverride?: string): Observable<Hypermedia> | any {
        const href = (scope === 'external') ? path : this.computeHref(path, scope);
        let headers = this.headerProvider.getHeaders(authorize, tokenOverride);
        // Check if is extern api - tradecore
        if (scope === 'external') {
            headers = headers.append('Accept', 'application/vnd.siren+json');
        }

        return this.http.get(href, {
            headers: headers,
            reportProgress: true
        }).pipe(
            map(data => data as Hypermedia)
        )
    }

    private computeHref(path: string, scope: string = 'local'): string {
        const hrefFormatter = this.applicationScopeHrefFormatterProvider.getHrefFormatterForScope(scope);

        return hrefFormatter.makeHrefFromPath(path);
    }
}
