/*
 * Copyright 2023 VMware, Inc. All rights reserved. VMware Confidential
 */

import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map, mergeMap, Observable } from "rxjs";

@Injectable()
export class DataService {

    constructor(private http: HttpClient) {
    }

    getHighestApiVersion(): Observable<string> {
        return this.http.get("/api/versions", { headers: this.getLegacyApiJsonHeaders() }).pipe(
            map((response: any) => {
                return response.versionInfo[response.versionInfo.length - 1].version;
            }));
    }

    getOrgVdcNetworks(): Observable<any> {
        return this.getHighestApiVersion().pipe((mergeMap((highestApiVersion: string) => {
            return this.http.get("/cloudapi/1.0.0/orgVdcNetworks", { headers: this.getJsonHeaders(highestApiVersion) })
        })));
    }

    private getJsonHeaders(apiVersion: string): HttpHeaders {
        return new HttpHeaders({
            "Accept": `application/json; version=${apiVersion}`,
            "Authorization": `Bearer ${this.getToken()}`
        });
    }

    private getLegacyApiJsonHeaders(): HttpHeaders {
        return new HttpHeaders({
            "Accept": "application/*+json"
        });
    }

    private getToken(): string {
        return localStorage.getItem("jwt");
    }}
