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

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

  private _url: string;
  private _token: string = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJpc3MiOiJqb3NlLmJAaXR0ZWMubXgiLCJhdWQiOiJkb21pbmlvLnN5cC5teCIsImlhdCI6MTY0NzYxMjc0NCwiY2FkIjoxNjQ3Njk5MTQ0fQ.BkpH8BMrx0hExtdU0EsNGxQxcbx_RqvTpGq12DqfbS0IEej5enf6V6q2DbqPsueK_0DMR_CWU9kMMYQCN2jrCg';

  constructor(private _http: HttpClient) {
    this._url = `${apiUriJean}/generic`;

  }

  public registerData(data: any) {
    return this.postQuery("registra-form", data).pipe(map((data: any) => data))
  }

  public updateData(data: any) {
    return this.postQuery("modifica-form", data).pipe(map((data: any) => data))
  }

  public generateMenu(data: any) {
    return this.getQuery("generate-menu/" + data).pipe(map((data: any) => data))
  }

  public generateTable(data: any) {
    return this.postQuery("generate-table", data).pipe(map((data: any) => data))
  }

  public generateForm(id_form: string) {
    return this.getQuery("generate-form/" + id_form).pipe(map((data: any) => data))
  }

  public generateFormEdit(id_form: string, data_table: any) {
    return this.putQuery("consulta-info/" + id_form, data_table).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,
      }),
    });
  }

  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,
      }),
    });
  }
}
