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

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

  constructor(private http: HttpClient) {}

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

  getFiles(mod: string, cla: string, sda: string, eda: string, dna: string, idUser: string, line: number){
    return this.getQueryTmp(`get-files/${mod}/${cla}/${sda}/${eda}/${dna}/${idUser}/${line}`).pipe(map((data: any) => data));
  }

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

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

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

  uploadTempFile(body: any) {
    return this.postQuery('upload-file', body).pipe(map((data: any) => data));
  }

  deleteTempFile(body: any) {
    return this.postQuery('delete-file', body).pipe(map((data: any) => data));
  }

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

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