import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs';
import { apiTemp } from '../../environments/environment.prod';

@Injectable({
  providedIn: 'root'
})
export class CataloguesService {

  constructor(private _http: HttpClient) {}

  getCatalogues(id: string, line: number){
    return this.getQuery(`get-catalogues/${id}/${line}`).pipe(map((data: any) => data));
  }

  generateDownloadToken(idUser: string, type: string){
    return this.getQuery(`generate-download-token/${idUser}/${type}`).pipe(map((data: any) => data));
  }

  readCatalogue(id: string, idUser: string, line: number){
    return this.getQuery(`read-catalogue/${id}/${idUser}/${line}`).pipe(map((data: any) => data));
  }

  getGeneralCatalogueInfo(catalogue:string, header:number, user:string, line: number) {
    return this.getQuery(`get-general-catalogue-info/${catalogue}/${header}/${user}/${line}`).pipe(map((data: any) => data));
  }

  getQuery(query: string){
    const JWT = `Bearer ${localStorage.getItem('token')}`;
    const URL = `${apiTemp}${query}`;
    return this._http.get(URL, {
      headers: new HttpHeaders({
        Authorization: JWT
      })
    });
  }

  uploadCatalogue(body: any){
    return this.postQuery("upload-catalogue", body).pipe(map((data: any) => data));
  }

  postQuery(query: string, body: any){
    const JWT = `Bearer ${localStorage.getItem('token')}`;
    const URL = `${apiTemp}${query}`;
    return this._http.post(URL, body, {
      headers: new HttpHeaders({
        Authorization: JWT!
      })
    });
  }
}
