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

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

  private _url:string; 
  private _token:string;

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

  // Obtener submodulos
  public getSubmodules() {
    return this.getQuery("consulta").pipe(map((data: any) => data))
  }

  // Obtener Submódulos por Módulos
  public getOneSubmodule(data: any) {
    return this.getQuery("consulta/" + data).pipe(map((data: any) => data))
  }

  // Registro de Submódulos
  public postSubmodules(data: any) {
    return this.postQuery("registra", data).pipe(map((data: any) => data))
  }

  // Modificar Submódulos
  public updateSubmodules(data: any) {
    return this.postQuery("modifica", data).pipe(map((data: any) => data))
  }

  // Eliminar Submódulos
  public deleteSubmodule(codigo: any) {
    return this.postQuery("elimina", codigo).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
      })
    });
  }
}
