import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
import { apiUriJean } from 'src/environments/environment';
import { ResponseData } from '../../validations.service';

@Injectable({
  providedIn: 'root',
})
export class GETBTBService {
  private _url: string;
  private _token: string;

  constructor(private _http: HttpClient) {
    this._url = `${apiUriJean}/tabla-dyn`;
    this._token = `Bearer ${localStorage.getItem('token')}`;
  }

  // Consulta de Tablas Dinámicas
  public getTableDynamic() {
    return this.getQuery('consulta-table').pipe(map((data: any) => data));
  }

  // Obtener Columnas de Tablas
  /* public getColumns(data:any): Observable<ResponseData>{
    return this.postQuery("consulta-columnas", data).pipe(map((data: any) => data));
  }
 */
  // Obtener Tabla de Ejemplo
  public getDataTable(data: any) {
    return this.postQuery('consulta-datos', data).pipe(
      map((data: any) => data)
    );
  }

  public getTable(idTable: any) {
    return this.getQuery(`consulta-data/${idTable}`).pipe(
      map((data: any) => data)
    );
  }

  // Registrar Tabla Dinámica
  public saveTable(data: any) {
    return this.postQuery('registra-table', data).pipe(
      map((data: any) => data)
    );
  }

  private getQuery(query: string) {
    const URL = `${this._url}/${query}`;
    return this._http.get(URL, {
      headers: new HttpHeaders({
        Authorization: this._token,
      }),
    });
  }

  updateTable(id_table: any, table: any) {
    return this.putQuery(`modifica-table/${id_table}`, table).pipe(
      map((data: any) => data)
    );
  }

  private postQuery(query: string, body: any) {
    const URL = `${this._url}/${query}`;
    return this._http.post(URL, body, {
      headers: new HttpHeaders({
        Authorization: this._token,
      }),
    });
  }

  private putQuery(query: string, body: any) {
    const URL = `${this._url}/${query}`;
    return this._http.put(URL, body, {
      headers: new HttpHeaders({
        Authorization: this._token,
      }),
    });
  }
}
