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 GETBFOService {
  private _url: string;
  private _token: string;

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

  // Obtener Formularios
  public getForm(): Observable<ResponseData> {
    return this.getQuery('consulta').pipe(map((data: any) => data));
  }

  // Creación de Formulaios
  public createForm(json: any) {
    return this.postQuery('registra', json).pipe(map((data: any) => data));
  }

  // Modificación de Formulario
  public updateForm(response: any, idForm: any) {
    return this.putQuery(`modifica/${idForm}`, response).pipe(
      map((data: any) => data)
    );
  }

  // Eliminar Formulario
  public deleteForm(codigo_form: any) {
    return this.postQuery('elimina', codigo_form).pipe(
      map((data: any) => data)
    );
  }

  // Obtener Formulario Único
  public getFormData(codigo_form: number): Observable<ResponseData> {
    return this.getQuery(`consulta-data/${codigo_form}`).pipe(
      map((data: any) => data)
    );
  }

  // Obtener Datos para un Select
  public getDataSelect(data: any): Observable<ResponseData> {
    return this.postQuery('consulta-select', 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,
      }),
    });
  }

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

export interface FormResponse {
  NOMBRE_FORM: string;
  MODULO: string;
  SUBMODULO: string;
}

export interface ResponseData {
  error: boolean;
  msg: string;
  response: Array<FormResponse>;
}
