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

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

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

  // Obtener Menús
  public getMenu() {
    return this.getQuery("consulta").pipe(map((data: any) => data));
  }

  // Obtener Menú por Submódulos para Formulario
  public getMenuByForm(data: any) {
    return this.getQuery("consulta-form/" + data).pipe(map((data: any) => data));
  }

  // Registrar Menú
  public registerMenu(formData: any) {
    return this.postQuery("registra", formData).pipe(map((data: any) => data));
  }

  // Modificar Menú
  public updateMenu(formData: any) {
    return this.postQuery("modifica", formData).pipe(map((data: any) => data));
  }

  // Eliminar Menú
  public deleteMenu(menu_code: any) {
    return this.postQuery("elimina", menu_code).pipe(map((menu_code: any) => menu_code));
  }

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